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

import android.text.TextUtils;
import android.view.LayoutInflater;
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.chad.library.adapter.base.BaseQuickAdapter;
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.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.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
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 MesTicketDetailFinishActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.btn_reviews)
    Button btnReviews;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @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.rv_annex)
    RecyclerView rvAnnex;
    @BindView(R.id.tv_finish_confirm)
    TextView tvFinishConfirm;
    private SummaryBean dataBean;
    private List<ImageBean> imgList;
    private ImgAdapter imgAdapter;
    private TicketBean.ListBean data;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        String from = getIntent().getStringExtra("from");
//        if (!TextUtils.isEmpty(from)) {
//            btnReviews.setVisibility(View.GONE);
//        } else {
//            btnReviews.setVisibility(View.VISIBLE);
//        }

        if (WorkUtils.hasMesMenuPermission(JSON.parseArray(getIntent().getStringExtra("permission")), "评价")) {
            btnReviews.setVisibility(View.VISIBLE);
        }
        rvImg.setLayoutManager(new GridLayoutManager(this, 3, RecyclerView.VERTICAL, false));
        rvAnnex.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

    }

    @Override
    protected void initData() {
        data = JSON.parseObject(getIntent().getStringExtra("data"), TicketBean.ListBean.class);
        tvCode.setText(data.getJobNo());
        changView();
        imgList = new ArrayList<>();
        imgAdapter = new ImgAdapter(R.layout.item_mes_ticket_img, imgList);
        imgAdapter.bindToRecyclerView(rvImg);
        getData();
    }

    /**
     * 评价
     *
     * @param id
     */
    private void openStar(int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_reviews, null);
        RecyclerView rvStar = view.findViewById(R.id.rv_reviews);
        TextView tvScore = view.findViewById(R.id.tv_score);
        StarAdapter starAdapter = WorkUtils.starView(rvStar, this);

        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        addCartDialog.show();
        starAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                starAdapter.setScore(position + 1);
                tvScore.setText(String.format("%s分", position + 1));
                review(position + 1);
                addCartDialog.dismiss();
            }
        });
    }

    private void review(int evaluationScore) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("evaluationScore", evaluationScore);
        param.put("jobNo", data.getJobNo());
        RtfUtils.getMesRtf().reviewAdd("1", "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;
                }
                toast("评价成功");
                EventBus.getDefault().post(new AddTicketEvent());
                btnReviews.setVisibility(View.GONE);
            }
        });
    }

    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();
            }
        });
    }

    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();
//        List<ImageBean> annexList =new ArrayList<>();
//        annexList.addAll(dataBean.getAttachmentId())
    }

    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);
        }
    }

    @Override
    protected void initEvent() {
    }

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


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

}
