package com.ewei.demo.ticket;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ewei.demo.R;
import com.ewei.demo.ticket.adapter.OpenTicketFixedFieldsAdapter;
import com.ewei.sdk.base.BaseActivity;
import com.ewei.sdk.constants.CommonValue;
import com.ewei.sdk.constants.TicketValue;
import com.ewei.sdk.entity.CreateTicketResult;
import com.ewei.sdk.entity.HttpErrorInfo;
import com.ewei.sdk.entity.NameValue;
import com.ewei.sdk.entity.ServiceCatalog;
import com.ewei.sdk.entity.Tag;
import com.ewei.sdk.entity.Ticket;
import com.ewei.sdk.entity.TicketProperty;
import com.ewei.sdk.entity.TicketType;
import com.ewei.sdk.listener.RequestListener;
import com.ewei.sdk.logic.TicketLogic;
import com.ewei.sdk.ticket.TicketTypeActivity;
import com.ewei.sdk.utility.ToastUtils;
import com.ewei.sdk.utility.Utils;
import com.ewei.sdk.widget.servicecatalog.ServiceCatalogWindow;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 提交工单
 *
 * @author Jay
 * @date 2018/12/2
 */
public class OpenSubmitTicketActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final String TAG = OpenSubmitTicketActivity.class.getSimpleName();

    private ListView mLvFrom;
    private OpenTicketFixedFieldsAdapter fieldsAdapter;
    private List<TicketProperty> mFFTypeList = new ArrayList<>();

    private ServiceCatalogWindow serviceCatalogWindow;
    private Ticket newTicket = new Ticket();
    private NameValue priority;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ewei_open_activity_submit_ticket);
        /**
         * 初始化服务目录
         */
        serviceCatalogWindow = new ServiceCatalogWindow(this);

        initView();
        initFrom();
    }


    /**
     * 初始化开放对应字段字段
     */
    private void initFrom() {
        if (mFFTypeList.size() > 0) {
            mFFTypeList.clear();
        }

        //主题
        TicketProperty tempTp = new TicketProperty();
        tempTp.name = "主题";
        tempTp.notes = "请输入工单主题";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_SUBJECT;
        tempTp.required = true;
        mFFTypeList.add(tempTp);

        //描述
        tempTp = new TicketProperty();
        tempTp.name = "描述";
        tempTp.notes = "请输入工单描述";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_DESCRIPTION;
        tempTp.required = false;
        mFFTypeList.add(tempTp);

        //类型
        tempTp = new TicketProperty();
        tempTp.name = "类型";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_TICKET_TYPE;
        tempTp.notes = "请选择工单类型";
        tempTp.required = false;
        mFFTypeList.add(tempTp);

        //服务目录
        tempTp = new TicketProperty();
        tempTp.name = "服务目录";
        tempTp.notes = "请选择工单服务目录";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_SERVICE_CATALOG;
        tempTp.required = false;
        mFFTypeList.add(tempTp);

        //优先级
        tempTp = new TicketProperty();
        tempTp.name = "优先级";
        tempTp.notes = "请选择工单优先级";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_PRIORITY;
        tempTp.required = false;
        mFFTypeList.add(tempTp);

        //标签
        tempTp = new TicketProperty();
        tempTp.name = "标签";
        tempTp.notes = "请选择工单标签";
        tempTp.systemFieldKey = TicketValue.PROPERTIES_TYPE_TAGS;
        tempTp.required = false;
        mFFTypeList.add(tempTp);

        fieldsAdapter.addDatas(mFFTypeList);
    }

    private void initView() {
        initTitle("提交工单", CommonValue.TITLE_TYPE_FINISH);
        setFinishClick("提交", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createTicket();
            }
        });

        mLvFrom = (ListView) findViewById(R.id.lv_submit_ticket);
        fieldsAdapter = new OpenTicketFixedFieldsAdapter(this);
        mLvFrom.setAdapter(fieldsAdapter);
        mLvFrom.setOnItemClickListener(this);
    }


    /**
     * 创建工单
     */
    private void createTicket() {

        /**
         * 获取uid，防止重复提交
         */
        newTicket.uId = Utils.getUid();

        List<TicketProperty> tempTpList = fieldsAdapter.getDatas();
        String content = "";
        for (TicketProperty ticketProperty : tempTpList) {
            switch (ticketProperty.systemFieldKey) {
                case TicketValue.PROPERTIES_TYPE_SUBJECT:
                    content = fieldsAdapter.getValueForKey(ticketProperty.systemFieldKey);
                    newTicket.subject = content;
                    break;
                case TicketValue.PROPERTIES_TYPE_DESCRIPTION:
                    content = fieldsAdapter.getValueForKey(ticketProperty.systemFieldKey);
                    newTicket.description = content;
                    break;
                default:
                    content = ticketProperty.content;
                    break;
            }

            if (TextUtils.isEmpty(content) && ticketProperty.required) {
                ToastUtils.showToast(ticketProperty.name + "不能为空");
                return;
            }
        }

        showLoadingDialog("");
        TicketLogic.getInstance().createTicketWithOutForm(newTicket, new RequestListener<CreateTicketResult>() {
            @Override
            public void onSuccess(CreateTicketResult resultData, boolean isSuccess) {
                hideLoadingDialog();
                if (isSuccess) {
                    ToastUtils.showToast("工单提交成功！");
                    TicketActivity.startTicketActivity(OpenSubmitTicketActivity.this, new Ticket(resultData.ticketId), TicketActivity.class, 0);
                    finish();
                }
            }

            @Override
            public void onFailure(HttpErrorInfo errorInfo) {
                hideLoadingDialog();
                if (errorInfo != null && TextUtils.isEmpty(errorInfo.error_description)) {
                    ToastUtils.showToast(errorInfo.error_description);
                } else {
                    ToastUtils.showToast("工单提交失败！");
                }
            }
        });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        TicketProperty tp = (TicketProperty) parent.getAdapter().getItem(position);
        Intent intent;

        if (!TextUtils.isEmpty(tp.systemFieldKey)) {
            switch (tp.systemFieldKey) {
                case TicketValue.PROPERTIES_TYPE_TICKET_TYPE:
                    //类型
                    intent = new Intent(this, TicketTypeActivity.class);
                    intent.putExtra(TicketValue.VALUE_TICKET_REQUIRED, tp.required);
                    intent.putExtra("type", newTicket.ticketType);
                    startActivityForResult(intent, TicketValue.REQUEST_TICKET_TYPE);
                    break;
                case TicketValue.PROPERTIES_TYPE_SERVICE_CATALOG:
                    //服务目录
                    if (serviceCatalogWindow != null && !serviceCatalogWindow.isShowing()) {
                        serviceCatalogWindow.initData(newTicket.serviceCatalog != null ? newTicket.serviceCatalog.id : null);
                        serviceCatalogWindow.setRequired(tp.required);
                        serviceCatalogWindow.show();
                        serviceCatalogWindow.setConfirmonClickListener(new ServiceCatalogWindow.ConfirmonClickListener() {
                            @Override
                            public void confirmClick(String clickStr, ServiceCatalog clickData) {
                                //更新工单服务目录
                                serviceCatalogWindow.hide();
                                newTicket.serviceCatalog = clickData;
                                updataValue(TicketValue.PROPERTIES_TYPE_SERVICE_CATALOG, clickStr);
                            }
                        });
                    }
                    break;
                case TicketValue.PROPERTIES_TYPE_PRIORITY:
                    //优先级
                    intent = new Intent(this, OpenTicketPriorityActivity.class);
                    intent.putExtra("priority", priority);
                    startActivityForResult(intent, TicketValue.REQUEST_TICKET_PRIORITY);
                    break;
                case TicketValue.PROPERTIES_TYPE_TAGS:
                    //标签
                    intent = new Intent(this, OpenTicketTagsActivity.class);
                    intent.putExtra("tags", (Serializable) newTicket.tags);
                    startActivityForResult(intent, TicketValue.REQUEST_TICKET_TAG);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TicketValue.REQUEST_TICKET_TYPE:
                    //类型
                    TicketType mTicketTypeData = data != null ? (TicketType) data.getSerializableExtra("type") : null;
                    String content = "";
                    if (mTicketTypeData != null) {
                        content = mTicketTypeData.name;
                    }
                    updataValue(TicketValue.PROPERTIES_TYPE_TICKET_TYPE, content);
                    newTicket.ticketType = mTicketTypeData;
                    break;
                case TicketValue.REQUEST_TICKET_PRIORITY:
                    //优先级
                    priority = data != null ? (NameValue) data.getSerializableExtra("priority") : null;
                    content = priority != null ? priority.name : "";
                    newTicket.priority = priority != null ? priority.value : "";
                    updataValue(TicketValue.PROPERTIES_TYPE_PRIORITY, content);
                case TicketValue.REQUEST_TICKET_TAG:
                    //标签
                    List<Tag> tags = (List<Tag>) data.getSerializableExtra("tags");
                    updataValue(TicketValue.PROPERTIES_TYPE_TAGS, extractTagContent(tags));
                    newTicket.tags = tags;
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 提起标签文本显示
     *
     * @param tags 标签
     * @return
     */
    private String extractTagContent(List<Tag> tags) {

        if (tags == null || tags.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (Tag tag : tags) {
            if (sb.toString().isEmpty()) {
                sb.append(tag.name);
            } else {
                sb.append(", " + tag.name);
            }
        }
        return sb.toString();
    }


    /**
     * 更新列表展示文本
     *
     * @param key     对应key
     * @param content 对应内容
     */
    private void updataValue(String key, String content) {
        for (TicketProperty ticketProperty : mFFTypeList) {
            if (Utils.equals(key, ticketProperty.systemFieldKey)) {
                ticketProperty.content = content;
                fieldsAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void finish() {
        hideSoftKeyboard(this);
        super.finish();
    }
}
