package com.yidianling.consultant

import android.annotation.SuppressLint
import android.text.TextUtils
import com.google.gson.Gson
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.mvp.base.SimplePresenter
import com.ydl.ydlcommon.utils.RxLifecycleUtils
import com.ydl.ydlcommon.utils.YDLAsyncUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.consultant.http.ExpertSearchDataManager
import com.yidianling.consultant.model.SearchApi
import com.yidianling.consultant.model.bean.AllFilter
import com.yidianling.consultant.model.bean.ExpertSearchBean
import com.yidianling.consultant.modular.singlton.ConsultAssistantDialogUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * 专家搜索页Presenter
 */
class ExpertSearchPresenter : SimplePresenter<IExpertSearchView>() {

    @SuppressLint("CheckResult")
    fun fetchListHead() {
        SearchApi.getSearchApi()
                .searchConditions()
                .compose(RxLifecycleUtils.bindToLifecycle(mView!!))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxUtils.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ resp ->
                    mView.onHeadFetched(resp)
                }, { t ->
                    HttpErrorUtils.handleError(BaseApp.getApp(), t)
                    mView.fetchFailed(t.message)
                })
    }

    /**
     * 加载缓存
     */
    fun localData(showType : Int){
        YDLAsyncUtils.asyncAsResult(object : YDLAsyncUtils.AsyncObjecyerResult{
            override fun doAsyncAction(): Any {
                return when(showType){
                    0 ->{//按专家
                        YDLCacheUtils.getDoctorListData()
                    }
                    1 ->{//按服务
                        YDLCacheUtils.getServerListData()
                    }
                    else ->{
                        YDLCacheUtils.getServerListData()
                    }
                }
            }

            override fun asyncResult(`object`: Any?) {
                //如果没有缓存数据，显示加载框
                if (`object` !is String || TextUtils.isEmpty(`object`)){
                    mView.showRefreshLayout()
                }

                if (`object` is String){
                    val gson = Gson()
                    val bean = gson.fromJson<ExpertSearchBean>(`object`,ExpertSearchBean::class.java)
//                    val bean = gson.fromJson<ExpertSearchBean>(`object`, object : TypeToken<ExpertSearchBean>() {}.type)
                    if(bean?.list != null){
                        when(showType){
                            0 ->{
                                mView.onDoctorListFetched(bean.list, 1, 1)
                            }
                            1 ->{
                                mView.onServiceListFetched(bean.list, 1, 1)
                            }
                            else ->{
                                mView.onServiceListFetched(bean.list, 1, 1)
                            }
                        }

                    }
                }
            }
        })
    }

    fun updateCache(showType: Int,searchBean: ExpertSearchBean){
        val gson = Gson()
        val json = gson.toJson(searchBean)
        when(showType){
            0 ->{
                YDLCacheUtils.saveDoctorListData(json)
            }
            1 ->{
                YDLCacheUtils.saveServerListData(json)
            }
        }
    }

    @SuppressLint("CheckResult")
    fun fetchListData(allFilter: AllFilter, page: Int) {
        //是否亲子教育字段
        ConsultAssistantDialogUtils.REALATION_EDUCATION = allFilter.categories.size==1&&allFilter.categories[0].cateId==23
        var showType = 0

        val sb = StringBuffer()
        sb.append("searchWord=").append(if(TextUtils.isEmpty(allFilter.searchWord)) "" else allFilter.searchWord)
        if (allFilter.categories.isNotEmpty()) {
            var categorys = allFilter.categories.map { it.cateId }.joinToString(",")
            if ("0" == categorys) {
                categorys = ""
            }
            sb.append("&categories=").append(categorys)
        }
        if (allFilter.sub.key != null) {
            sb.append("&city=").append(Integer.parseInt(allFilter.sub.key))
        }
        if (allFilter.region.key != null) {
            sb.append("&province=").append(Integer.parseInt(allFilter.region.key))
        }
        if (allFilter.reorder.key != null) {
            sb.append("&reorder=").append(allFilter.reorder.key)
        }
        if (allFilter.enquiries.isNotEmpty()) {
            sb.append("&enquirys=").append(allFilter.enquiries.map { it.key }.joinToString(","))
        }
        if (allFilter.ages.isNotEmpty()) {
            sb.append("&ages=").append(allFilter.ages.map { it.key }.joinToString(","))
        }
        if (allFilter.others.isNotEmpty()) {
            sb.append("&others=").append(allFilter.others.map { it.key }.joinToString(","))
        }
//        if (allFilter.showType.key != null) {
//            showType = allFilter.showType.key!!
//            sb.append("&showType=").append(allFilter.showType.key!!)
//        }
        if(allFilter.title.isNotEmpty()){
            sb.append("&title=").append(allFilter.title.map { it.key }.joinToString(","))
        }
        if (allFilter.priceRanges !=null) {
            sb.append("&minPrice=").append(allFilter.priceRanges?.minPrice)
            sb.append("&maxPrice=").append(allFilter.priceRanges?.maxPrice)
        }
        sb.append("&page=").append(page)
        ExpertSearchDataManager.getHttp().searchDoctor(sb.toString())
            .compose(RxLifecycleUtils.bindToLifecycle(mView!!))
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                if (null != it.list && !it.list!!.isEmpty()) {
//                    if (showType == 0) {
//                        mView.onDoctorListFetched(it.list!!, page, it.pages)
//                    } else {
//                        mView.onServiceListFetched(it.list!!, page, it.pages)
//                    }
                    mView.onDoctorListFetched(it.list!!, page, it.pages)
                    //更新缓存 只更新第一页的缓存
                    if (page == 1){
                        updateCache(showType,it)
                    }
                } else {
                    mView.fetchListEmpty("没有搜到相关信息，换个关键词看看吧")
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    mView.fetchListFailed(msg)
                }
            })
    }
}