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

import android.os.Bundle;
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.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.AddTicketEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.ReviewBean;
import com.wd.workoffice.bean.mesBean.SummaryBean;
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.ImgAdapter;
import com.wd.workoffice.ui.adapter.StarAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
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 io.reactivex.disposables.Disposable;

/**
 * 工单详情  已评价
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesTicketDetailReviewActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.rv_star)
    RecyclerView rvStar;
    @BindView(R.id.rv_img)
    RecyclerView rvData;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @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.tv_detail)
    TextView tvDetail;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.tv_finish_confirm)
    TextView tvFinishConfirm;
    @BindView(R.id.rl_finish)
    RelativeLayout rlFinish;
    private StarAdapter starAdapter;
    private List<ImageBean> imgList;
    private ImgAdapter imgAdapter;
    private SummaryBean dataBean;
    private TicketBean.ListBean data;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        data = JSON.parseObject(getIntent().getStringExtra("data"), TicketBean.ListBean.class);
        tvCode.setText(data.getJobNo());
        changView();
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rvStar.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
    }

    @Override
    protected void initData() {
        imgList = new ArrayList<>();
        imgAdapter = new ImgAdapter(R.layout.item_mes_ticket_img, imgList);
        imgAdapter.bindToRecyclerView(rvData);
        imgAdapter.notifyDataSetChanged();
        starAdapter = WorkUtils.starView(rvStar, this);
        getData();
    }

    @Override
    protected void initEvent() {
    }

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

    private void getData() {
        RtfUtils.getMesRtf().summaryDetail(data.getJobNo(), "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;
                }
                dataBean = JSON.parseObject(data.getData().toString(), SummaryBean.class);
                setViewData();
            }
        });
        RtfUtils.getMesRtf().review(data.getJobNo(), "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;
                }
                ReviewBean dataBean = JSON.parseObject(data.getData().toString(), ReviewBean.class);
                starAdapter.setScore(dataBean.getEvaluationScore());
                tvScore.setText(String.format("%s分", dataBean.getEvaluationScore()));
            }
        });
    }

    private void setViewData() {
        tvFinishConfirm.setText(dataBean.getDataCollectionStatus() == 1 ? "完成" : "未完成");
        if (TextUtils.equals(data.getJobTypeId(), "01")) {
            tvDesignConfirm.setText(dataBean.getProductDrawingConfirmation() == 1 ? "确认" : "未确认");
            etDesign1.setText(dataBean.getSiteInvestigation());
            etDesign2.setText(dataBean.getFeasibilityReport());
        } else if (TextUtils.equals(data.getJobTypeId(), "02")) {
            etTry1.setText(dataBean.getExperimentProcess());
            etTry2.setText(dataBean.getExperimentResult());
            etTry3.setText(dataBean.getImproveProposal());
        } else if (TextUtils.equals(data.getJobTypeId(), "03")) {
            etQuality1.setText(dataBean.getFeedbackQualityIssues());
            etQuality2.setText(dataBean.getSiteUseSituation());
            etQuality3.setText(dataBean.getCauseAnalysis());
            etQuality4.setText(dataBean.getSolution());
        } else if (TextUtils.equals(data.getJobTypeId(), "04")) {
            etTech1.setText(dataBean.getCommunicativePurposes());
            etTech2.setText(dataBean.getCommunicativeSituation());
            etTech3.setText(dataBean.getReachOpinion());
        } else if (TextUtils.equals(data.getJobTypeId(), "05")) {
            etTender1.setText(dataBean.getProductDevise());
            etTender2.setText(dataBean.getProductQuotedPrice());
        }
        if (!TextUtils.isEmpty(dataBean.getProductsCode())) {
            tvQualityPro.setText(dataBean.getProductsName());
            tvTechPro.setText(dataBean.getProductsName());
            tvTryPro.setText(dataBean.getProductsName());
        }
        tvFinish.setText(dataBean.getCommunicativeSituation());
        imgList.addAll(dataBean.getAttachments());
        imgAdapter.notifyDataSetChanged();
    }

    private void changView() {
        if (TextUtils.equals(data.getJobTypeId(), "01")) {
            llDesign.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(data.getJobTypeId(), "02")) {
            llTry.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(data.getJobTypeId(), "03")) {
            llQuality.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(data.getJobTypeId(), "04")) {
            llTech.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(data.getJobTypeId(), "05")) {
            llTender.setVisibility(View.VISIBLE);
        } else {
//            rlFinish.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.tv_detail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_detail:
                startActivity(MesTicketDetailActivity.class, "data", JSON.toJSONString(data));
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (TextUtils.equals(data.getCreateUserId(), UserKeeper.getInstance().getMesUid())
                && data.getJobStatus() != 9)
            getMenuInflater().inflate(R.menu.menu_close, menu);
        return super.onCreateOptionsMenu(menu);
    }

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

    private void close(String content) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("content", content);
        param.put("id", data.getId());
        param.put("beforeStatus", data.getJobStatus());
        RtfUtils.getMesRtf().closeJob("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();
                toast("关闭成功");
                EventBus.getDefault().post(new AddTicketEvent());
            }
        });

    }

    private void closeDialog() {
        QMUIDialog.CustomDialogBuilder msg = DialogUtils.customDialog(this);
        msg.setLayout(R.layout.view_close_job);
        QMUIDialog qmuiDialog = msg.create();
        qmuiDialog.setCancelable(false);

        EditText etContent = qmuiDialog.findViewById(R.id.et_content);
        Button btnCancel = qmuiDialog.findViewById(R.id.btn_cancel);

        Button btnOk = qmuiDialog.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = etContent.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    toast("请输入关闭原因");
                    return;
                }
                close(content);
                qmuiDialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qmuiDialog.dismiss();
                finish();
            }
        });
        qmuiDialog.show();
    }

}
