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

import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
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.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.JobTypeBean;
import com.wd.workoffice.bean.mesBean.MesClientBean;
import com.wd.workoffice.bean.mesBean.TakeOnBean;
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.JobTypeAdapter;
import com.wd.workoffice.util.DialogUtils;
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.annotation.Nullable;
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 MesTicketAddActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_client)
    TextView tvClient;
    @BindView(R.id.rl_client)
    RelativeLayout rlClient;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.rl_company)
    RelativeLayout rlCompany;
    @BindView(R.id.tv_manager)
    TextView tvManager;
    @BindView(R.id.rl_manager)
    RelativeLayout rlManager;
    @BindView(R.id.tv_mark)
    TextView tvMark;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.rv_job)
    RecyclerView rvJob;
    @BindView(R.id.rl_job)
    RelativeLayout rlJob;
    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.tv_take_on)
    TextView tvTakeOn;
    @BindView(R.id.rl_take_on)
    RelativeLayout rlTakeOn;
    @BindView(R.id.et_person)
    EditText etPerson;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    private Map<String, Object> param;
    private QMUIDialog.MenuDialogBuilder jobDialog;
    private JobTypeBean chooseJob;
    private MesClientBean.ListBean chooseClient;
    private TakeOnBean.ListBean chooseTakeOn;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        param = WorkUtils.simpleParam();
        jobDialog = DialogUtils.listDialog(this);
        rvJob.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
    }

    @Override
    protected void initData() {
        String data = getIntent().getStringExtra("data");
        if (!TextUtils.isEmpty(data)) {
            TicketBean.ListBean ticketBean = JSON.parseObject(data, TicketBean.ListBean.class);
            tvClient.setText(ticketBean.getCustomerUserName());
            tvCompany.setText(ticketBean.getSalesCompanyName());
            tvManager.setText(ticketBean.getSalesManagerName());
            tvTakeOn.setText(ticketBean.getJobUserName());
            etDesc.setText(ticketBean.getJobDescription());
            etPerson.setText(ticketBean.getPeopleCount());
            tvStartTime.setText(ticketBean.getPlanBeginDate());
            tvEndTime.setText(ticketBean.getPlanEndDate());
            tvJob.setText(ticketBean.getJobTypeName());
//            param.put("jobNo", ticketBean.getJobNo());
            param.put("id", ticketBean.getId());
            if (!TextUtils.isEmpty(ticketBean.getCustomerUserCode())) {
                MesClientBean.ListBean newClient = new MesClientBean.ListBean();
                newClient.setCustomerCode(ticketBean.getCustomerUserCode());
                newClient.setCustomerName(ticketBean.getCustomerUserName());
                newClient.setSalesCompanyCode(ticketBean.getSalesCompanyCode());
                newClient.setSalesCompanyName(ticketBean.getSalesCompanyName());
                newClient.setSalesManagerCode(ticketBean.getSalesManagerCode());
                newClient.setSalesManagerName(ticketBean.getSalesManagerName());
                chooseClient = newClient;
            }
            if (!TextUtils.isEmpty(ticketBean.getJobTypeId())) {
                JobTypeBean jobTypeBean = new JobTypeBean();
                jobTypeBean.setJobTypeCode(ticketBean.getJobTypeId());
                jobTypeBean.setJobTypeName(ticketBean.getJobTypeName());
                chooseJob = jobTypeBean;
                getJobTypeChild(ticketBean.getJobTypeId());
            }
            if (!TextUtils.isEmpty(ticketBean.getJobUserId())) {
                TakeOnBean.ListBean takeOn = new TakeOnBean.ListBean();
                takeOn.setId(ticketBean.getJobUserId());
                takeOn.setName(ticketBean.getJobUserName());
                chooseTakeOn = takeOn;
            }
        }
        getJobType();
    }

    private void getJobType() {
        RtfUtils.getMesRtf().jobType("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;
                }
                List<JobTypeBean> jobTypeList = JSON.parseArray(data.getData().toString(), JobTypeBean.class);
                List<String> jobNameList = new ArrayList<>();
                for (JobTypeBean jobTypeBean : jobTypeList) {
                    jobNameList.add(jobTypeBean.getJobTypeName());
                }
                jobDialog.addItems(jobNameList.toArray(new String[jobNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseJob = jobTypeList.get(which);
                        tvJob.setText(jobNameList.get(which));
                        getJobTypeChild(chooseJob.getJobTypeCode());
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    private void getJobTypeChild(String jobTypeCode) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("jobTypeCode", jobTypeCode);
        RtfUtils.getMesRtf().jobTypeChild("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<JobTypeBean> jobTypeList = JSON.parseArray(data.getData().toString(), JobTypeBean.class);
                JobTypeAdapter jobTypeAdapter = new JobTypeAdapter(R.layout.item_job_type, jobTypeList);
                jobTypeAdapter.bindToRecyclerView(rvJob);
            }
        });
    }

    @Override
    protected void initEvent() {
    }

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


    @OnClick({R.id.tv_save, R.id.tv_submit, R.id.tv_start_time, R.id.tv_end_time, R.id.rl_job, R.id.rl_client, R.id.rl_company, R.id.rl_manager, R.id.rl_take_on})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_save:
                param.put("jobStatus", 0);
                submit();
                break;
            case R.id.tv_submit:
                if (chooseClient == null) {
                    toast("请选择客户");
                    return;
                }
                if (chooseJob == null) {
                    toast("请选择任务类别");
                    return;
                }
                if (chooseTakeOn == null) {
                    toast("请选择任务担当");
                    return;
                }
                param.put("jobStatus", 1);
                submit();
                break;
            case R.id.rl_job:
                jobDialog.show();
                break;
            case R.id.rl_client:
                startActivityForResult(MesTicketClientActivity.class, 10001);
                break;
            case R.id.rl_company:
                break;
            case R.id.rl_manager:
                break;
            case R.id.rl_take_on:
                startActivityForResult(MesTicketTakeOnActivity.class, 10002);
                break;
            case R.id.tv_start_time:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvStartTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
                    }
                }).show();
                break;
            case R.id.tv_end_time:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvEndTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
                    }
                }).show();
                break;
        }
    }

    private void submit() {
        String startTime = tvStartTime.getText().toString();
        String endTime = tvEndTime.getText().toString();
        if (TextUtils.isEmpty(startTime)||TextUtils.isEmpty(endTime)){
            toast("请选择开始结束时间");
            return;
        }
        if (chooseClient != null) {
            param.put("customerUserCode", chooseClient.getCustomerCode());
            param.put("customerUserName", chooseClient.getCustomerName());
            param.put("salesCompanyCode", chooseClient.getSalesCompanyCode());
            param.put("salesCompanyName", chooseClient.getSalesCompanyName());
            param.put("salesManagerCode", chooseClient.getSalesManagerCode());
            param.put("salesManagerName", chooseClient.getSalesManagerName());
        }
        if (chooseJob != null) {
            param.put("jobTypeId", chooseJob.getJobTypeCode());
            param.put("jobTypeName", chooseJob.getJobTypeName());
        }
        if (chooseTakeOn != null) {
            param.put("jobUserId", chooseTakeOn.getId());
            param.put("jobUserName", chooseTakeOn.getName());
        }
        param.put("jobDescription", etDesc.getText().toString());
        param.put("peopleCount", etPerson.getText().toString());
        param.put("planBeginDate", tvStartTime.getText().toString() + " 00:00:00");
        param.put("planEndDate", tvEndTime.getText().toString() + " 00:00:00");
        RtfUtils.getMesRtf().ticketAdd("1", TextUtils.isEmpty(getIntent().getStringExtra("data")) ? "1" : "2", 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());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            chooseClient = JSON.parseObject(data.getStringExtra("data"), MesClientBean.ListBean.class);
            tvClient.setText(chooseClient.getCustomerName());
            tvCompany.setText(chooseClient.getSalesCompanyName());
            tvManager.setText(chooseClient.getSalesManagerName());
        } else if (requestCode == 10002 && resultCode == 10002) {
            chooseTakeOn = JSON.parseObject(data.getStringExtra("data"), TakeOnBean.ListBean.class);
            tvTakeOn.setText(chooseTakeOn.getName());
        }
    }

}
