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

import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.Config;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.mesBean.MesServiceCheckBillBean;
import com.wd.workoffice.bean.mesBean.ServiceCheckBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.MesServiceCheckDetailAdapter;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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.TimeUtils;
import io.reactivex.disposables.Disposable;

/**
 * 点检详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class ServiceCheckDetailActivity 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_status)
    TextView tvStatus;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_new_person)
    TextView tvNewPerson;
    @BindView(R.id.tv_new_time)
    TextView tvNewTime;
    @BindView(R.id.tv_machine)
    TextView tvMachine;
    @BindView(R.id.tv_factory)
    TextView tvFactory;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.tv_plan_star_time)
    TextView tvPlanStarTime;
    @BindView(R.id.tv_plan_end_time)
    TextView tvPlanEndTime;
    @BindView(R.id.tv_change_star_time)
    TextView tvChangeStarTime;
    @BindView(R.id.tv_change_end_time)
    TextView tvChangeEndTime;
    @BindView(R.id.tv_true_star_time)
    TextView tvTrueStarTime;
    @BindView(R.id.tv_true_end_time)
    TextView tvTrueEndTime;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.rl_true_star_time)
    RelativeLayout rlTrueStarTime;
    @BindView(R.id.rl_true_end_time)
    RelativeLayout rlTrueEndTime;
    private Map<String, Object> param;
    private List<MesServiceCheckBillBean.ListBean> dataList;
    private MesServiceCheckDetailAdapter dataAdapter;
    private ServiceCheckBean.ListBean info;
    private int page = 1;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvData.setNestedScrollingEnabled(false);
    }


    @Override
    protected void initData() {
        info = JSON.parseObject(getIntent().getStringExtra("info"), ServiceCheckBean.ListBean.class);
        changeView();

        dataList = new ArrayList<>();
        dataAdapter = new MesServiceCheckDetailAdapter(R.layout.item_mes_service_check, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = WorkUtils.pageMesKey();
        Map<String, Object> paramMap = WorkUtils.simpleParam();
        param.put("paramMap", paramMap);
        param.put("length", 15);
        paramMap.put("billId", info.getId());
        param.put("pageNum", page);
        getDetail();
        getData();
    }

    private void changeView() {
        tvNo.setText(info.getBillNum());
        tvStatus.setText(info.getStatus() == 2 ? "待执行" : "已完成");
        if (info.getStatus() != 2) {
            llBottom.setVisibility(View.GONE);
        }
        tvPerson.setText(info.getSpotCheckPersonName());
        tvNewPerson.setText(info.getCreateUserName());
        tvNewTime.setText(info.getCreateDateTime());
        tvMachine.setText(info.getAstAssetName());
        tvFactory.setText(info.getSiteName());
        tvRemark.setText(info.getBillDescription());

        tvPlanStarTime.setText(info.getBeginTimePlan());
        tvPlanEndTime.setText(info.getEndTimePlan());
        tvChangeStarTime.setText(info.getBeginTimeAdjust());
        tvChangeEndTime.setText(info.getEndTimeAdjust());
        tvTrueStarTime.setText(info.getBeginTimeActual());
        tvTrueEndTime.setText(info.getEndTimeActual());
    }

    private void getDetail() {
        RtfUtils.getMesRtf().spotCheckDetail(info.getId(), "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;
                }
                info = JSON.parseObject(data.getData().toString(), ServiceCheckBean.ListBean.class);
                changeView();
            }
        });
    }


    private void getData() {
        RtfUtils.getMesRtf().spotCheckBillProject("00d12c310f4411ea8334fa163e1166bd", 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;
                }
                List<MesServiceCheckBillBean.ListBean> getList = JSON.parseObject(data.getData().toString(), MesServiceCheckBillBean.class).getList();
                if (page == 1) {
                    dataList.clear();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                    dataAdapter.loadMoreComplete();
                } else {
                    dataAdapter.loadMoreComplete();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                }
                if (getList.size() == 0 || getList.size() < Config.SIZE) {
                    dataAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        dataAdapter.setOnLoadMoreListener(() -> {
            param.put("pageNum", page);
            getData();
        }, rvData);
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                startActivity(ServiceStandardActivity.class, "id", dataList.get(i).getId(),
                        "info", JSON.toJSONString(info),
                        "machine", JSON.toJSONString(dataList.get(i)), "type", getIntent().getStringExtra("type"));
            }
        });
    }


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

    @OnClick({R.id.tv_refuse, R.id.tv_agree, R.id.rl_true_star_time, R.id.rl_true_end_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_refuse:
                save();
                break;
            case R.id.tv_agree:
                finishRequest();
                break;
            case R.id.rl_true_star_time:
                PickTimeUtils.showPickTime(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View view) {
                        tvTrueStarTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("HH:mm:ss")));
                        info.setBeginTimeActual(tvTrueStarTime.getText().toString());
//                        paramMap.put("createDateTime", TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
//                        page = 1;
//                        param.put("pageNum", page);
//                        getData();
                    }
                }, false).show(rlTrueStarTime);
                break;
            case R.id.rl_true_end_time:
                PickTimeUtils.showPickTime(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View view) {
                        tvTrueEndTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("HH:mm:ss")));
                        info.setEndTimeActual(tvTrueEndTime.getText().toString());
//                        paramMap.put("createDateTime", TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
//                        page = 1;
//                        param.put("pageNum", page);
//                        getData();
                    }
                }, false).show(rlTrueEndTime);
                break;
        }
    }

    private void save() {
        info.setStatus(2);
        RtfUtils.getMesRtf().spotCheckBillUpdate("00d12c310f4411ea8334fa163e1166bd",
                WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info)))).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("保存成功");
                finish();
            }
        });
    }

    private void finishRequest() {
        info.setStatus(3);
        RtfUtils.getMesRtf().spotCheckBillUpdate("00d12c310f4411ea8334fa163e1166bd",
                WorkUtils.convertMapToBody(JSON.parseObject(JSON.toJSONString(info)))).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());
                    info.setStatus(null);
                    return;
                }
                toast("保存成功");
                finish();
            }
        });
    }
}
