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

import android.os.Bundle;
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.event.ChangeStatus;
import com.wd.workoffice.bean.mesBean.MesServiceBillBean;
import com.wd.workoffice.bean.mesBean.ServiceBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.MesServiceDetailAdapter;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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 ServiceDetailActivity 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_plan)
    TextView tvPlan;
    @BindView(R.id.tv_machine)
    TextView tvMachine;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @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;
    @BindView(R.id.tv_close)
    TextView tvClose;
    private Map<String, Object> param;
    private List<MesServiceBillBean.ListBean> dataList;
    private MesServiceDetailAdapter dataAdapter;
    private ServiceBean.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"), ServiceBean.ListBean.class);
        changeView();
        dataList = new ArrayList<>();
        dataAdapter = new MesServiceDetailAdapter(R.layout.item_mes_service, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = WorkUtils.pageMesKey();
        Map<String, Object> paramMap = WorkUtils.simpleParam();
        param.put("paramMap", paramMap);
        paramMap.put("inspoId", info.getId());
        param.put("pageNum", page);
        getData();
    }

    private void changeView() {
        //   1 待执行   2已完成
        tvNo.setText(info.getInspoCode());
        tvClose.setText(info.getStopWork() == 1 ? "是" : "否");
        tvStatus.setText(info.getStatus() == 2 ? "已完成" : "待执行");
        if (info.getStatus() == 2) {
            llBottom.setVisibility(View.GONE);
        }
        tvPerson.setText(info.getPrincipalName());
        tvPlan.setText(info.getPlanDesc());
        tvLocation.setText(info.getLocationName());
        tvMachine.setText(info.getAssetDesc());
        tvFactory.setText(info.getSiteDesc());
        tvRemark.setText(info.getDescription());

//        tvPlanStarTime.setText(info.getPlanStartDateTime());
//        tvPlanEndTime.setText(info.getPlanEndDateTime());
        tvChangeStarTime.setText(info.getAdjustBeginTime());
        tvChangeEndTime.setText(info.getAdjustEndTime());
        tvTrueStarTime.setText(info.getActualStartDateTime());
        tvTrueEndTime.setText(info.getActualEndDateTime());

    }


    private void getData() {
        RtfUtils.getMesRtf().modinspoproject("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;
                }
                List<MesServiceBillBean.ListBean> getList = JSON.parseObject(data.getData().toString(), MesServiceBillBean.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++;
                }
            }
        });
        RtfUtils.getMesRtf().modinspoDetail( 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;
                }
                ServiceBean.ListBean   dataBean = JSON.parseObject(data.getData().toString(), ServiceBean.ListBean.class);
                info.setAssetId(dataBean.getAssetId());
            }
        });
    }

    @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", "1"
                ,_TITLE,"检修项目");
            }
        });
    }


    @Override
    protected int layoutId() {
        return R.layout.activity_mes_service_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.showPick(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View view) {
                        tvTrueStarTime.setText(TimeUtils.date2String(date));
                        info.setActualStartDateTime(tvTrueStarTime.getText().toString());

//                        paramMap.put("createDateTime", TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
//                        page = 1;
//                        param.put("pageNum", page);
//                        getData();
                    }
                }).show();
                break;
            case R.id.rl_true_end_time:
                PickTimeUtils.showPick(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View view) {
                        tvTrueEndTime.setText(TimeUtils.date2String(date));
                        info.setActualEndDateTime(tvTrueEndTime.getText().toString());
//                        paramMap.put("createDateTime", TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
//                        page = 1;
//                        param.put("pageNum", page);
//                        getData();
                    }
                }).show();
                break;
        }
    }

    private void save() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("id", info.getId());
        param.put("inspoCode", info.getInspoCode());
        param.put("status", 1);
        param.put("actualEndDateTime", info.getActualEndDateTime());
        param.put("actualStartDateTime", info.getActualStartDateTime());
        RtfUtils.getMesRtf().modinspoprojectUpdate("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;
                }
                EventBus.getDefault().post(new ChangeStatus());
                toast("保存成功");
                finish();
            }
        });
    }

    private void finishRequest() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("status", "2");
        param.put("id", info.getId());
        param.put("inspoCode", info.getInspoCode());
        param.put("actualEndDateTime", info.getActualEndDateTime());
        param.put("actualStartDateTime", info.getActualStartDateTime());
        RtfUtils.getMesRtf().modinspoprojectUpdate("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;
                }
                EventBus.getDefault().post(new ChangeStatus());
                toast("保存成功");
                finish();
            }
        });
    }

}
