package com.yidianling.consultant

import android.annotation.SuppressLint
import android.text.TextUtils
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.base.SimplePresenter
import com.ydl.ydlcommon.utils.RxLifecycleUtils
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
import com.yidianling.common.tools.RxAppTool
import com.yidianling.common.tools.ToastUtil
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.Extras
import com.yidianling.user.api.service.IUserService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * 专家搜索页Presenter
 */
class ExpertSearchPresenter : SimplePresenter<IExpertSearchView>() {
    var mExtras: Extras? =null // 用于分页

    @SuppressLint("CheckResult")
    fun fetchListHead() {
        SearchApi.getSearchApi()
            .searchConditions(2)
            .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)
            })
    }


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

        val map = HashMap<String, Any>()
        // filter
        val filterMap = HashMap<String, Any?>()
        // 搜索词
        if (!TextUtils.isEmpty(allFilter.searchWord)){
            filterMap["__keywords"] = allFilter.searchWord
        }
        val categoryList = ArrayList<Any>()
        // 八大类一级标签
        if (allFilter.categoryId2List.size>0){
            val categoryMap2 = HashMap<String, Any>()
            val categoryIdMap2 = HashMap<String, Any>()
            categoryIdMap2["in"] = allFilter.categoryId2List.toSortedSet().toList()
            categoryMap2["product_cates.category_id2"] = categoryIdMap2
            categoryList.add(categoryMap2)
        }
        // 八大类二级标签
        if (allFilter.categoryId3List.size>0){
            val categoryMap3 = HashMap<String, Any>()
            val categoryIdMap3 = HashMap<String, Any>()
            categoryIdMap3["in"] = allFilter.categoryId3List.toSortedSet().toList()
            categoryMap3["product_cates.category_id3"] = categoryIdMap3
            categoryList.add(categoryMap3)
        }
        if (categoryList.size>0){
            filterMap["__or"] = categoryList
        }
        // 主题
        if (allFilter.categories.size>0) {
            val categories = ArrayList<String?>()
            allFilter.categories.forEach {
                categories.add(it.cateId)
            }
            val categoriesMap = HashMap<String, Any>()
            categoriesMap["in"] = categories
            filterMap["tags.tag_id"] = categoriesMap
        }
        // 地区
        if (allFilter.region.value == "海外") {
            filterMap["country_code"] = allFilter.sub.code
        } else{
            if (allFilter.region.code != null&&allFilter.region.code!="1") {
                filterMap["province_code"] = allFilter.region.code
            }
            if (allFilter.sub.code != null&&allFilter.sub.code!=allFilter.region.code) {
                filterMap["city_code"] = allFilter.sub.code
            }
        }
        // 咨询方式
        if (allFilter.enquiries.isNotEmpty()) {
            val way = ArrayList<Int>()
            allFilter.enquiries.forEach {
                way.add(it.key)
            }
            val wayMap = HashMap<String, Any>()
            wayMap["in"] = way
            filterMap["product_specs.spec_id"] = wayMap
        }
        // 服务均价
        if (allFilter.priceRanges != null) {
            val avgPriceMap = HashMap<String, Any?>()
            avgPriceMap["gte"] = allFilter.priceRanges?.minPrice
            avgPriceMap["lte"] = allFilter.priceRanges?.maxPrice
            filterMap["avg_price"] = avgPriceMap
        }
        // 年龄
        if (allFilter.ages.isNotEmpty()) {
            val age = ArrayList<Int>()
            allFilter.ages.forEach {
                age.add(it.key)
            }
            val ageMap = HashMap<String, Any>()
            ageMap["in"] = age
            filterMap["years"] = ageMap
        }
        // 资质
        if (allFilter.title.isNotEmpty()) {
            val title = ArrayList<String?>()
            allFilter.title.forEach {
                title.add(it.key)
            }
            val titleMap = HashMap<String, Any>()
            titleMap["in"] = title
            filterMap["titles.title"] = titleMap
        }
        // 擅长人群
        if (allFilter.specialityCrowd.isNotEmpty()) {
            val specialityCrowd = ArrayList<String?>()
            allFilter.specialityCrowd.forEach {
                specialityCrowd.add(it.key)
            }
            val specialityCrowdMap = HashMap<String, Any>()
            specialityCrowdMap["in"] = specialityCrowd
            filterMap["doctor_tag_list.list.tag_id"] = specialityCrowdMap
        }
        // 学历
        if (allFilter.doctorEdu.isNotEmpty()) {
            val edu = ArrayList<Int?>()
            allFilter.doctorEdu.forEach {
                edu.add(it.key)
            }
            val eduMap = HashMap<String, Any>()
            eduMap["in"] = edu
            filterMap["edu"] = eduMap
        }
        // 其它
        if (allFilter.others.isNotEmpty()) {
            val gender = ArrayList<String?>()
            allFilter.others.forEach {
                when (it.key1) {
                    "gender" -> {
                        gender.add(it.value1)
                    }
                    else -> {
                        filterMap[it.key1] = it.value1
                    }
                }
            }
            if (gender.size>0){
                val genderMap = HashMap<String, Any>()
                genderMap["in"] = gender
                filterMap["gender"] = genderMap
            }
        }
        map["filter"] = filterMap

        // sorts
        if (allFilter.reorder.key != null) {
            val sortsMap = HashMap<String, Any>()
            sortsMap[allFilter.reorder.key1] = allFilter.reorder.value1
            map["sorts"] = sortsMap
        }
        // fields
        val fieldsMap = HashMap<String, Any>()
        fieldsMap["doctor_id"] = true
        fieldsMap["doctor_name"] = true
        fieldsMap["uid"] = true
        fieldsMap["chat_status"] = true
        fieldsMap["gender"] = true
        fieldsMap["years"] = true
        fieldsMap["head"] = true
        fieldsMap["edu"] = true
        fieldsMap["province"] = true
        fieldsMap["city"] = true
        fieldsMap["evaluation_average_score"] = true
        fieldsMap["evaluate_num"] = true
        fieldsMap["min_price"] = true
        fieldsMap["title"] = true
        fieldsMap["famous_remark"] = true
        fieldsMap["help_num"] = true
        fieldsMap["p30d_sold_hour"] = true
        fieldsMap["sum_service_time"] = true
        fieldsMap["has_servicefree_consult"] = true
        fieldsMap["is_new_enter"] = true
        fieldsMap["chat_num"] = true
        fieldsMap["chat_btn_text"] = true
        fieldsMap["feature_tags"] = true
        fieldsMap["link_url"] = true
        fieldsMap["open_chat_agency"] = true
        fieldsMap["service_status"] = true
        fieldsMap["is_free_today"] = true
        map["fields"] = fieldsMap

        val optionsMap = HashMap<String, Any?>()
        optionsMap["search_scene_id"] = "doctor_main_search"
        optionsMap["uid"] = ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid
        optionsMap["ffrom"] = PlatformDataManager.getRam().getChannelName()
        optionsMap["version"]= RxAppTool.getAppVersionName(BaseApp.getApp())
        optionsMap["os_type"]= 2
        if (extras!=null){
            optionsMap["extras"] = extras
        }
        map["options"] = optionsMap


        ExpertSearchDataManager.getHttp()
            .getExpertList(map)
            .compose(RxLifecycleUtils.bindToLifecycle(mView))
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                // 当前页数
                val curPage = (it.skip/it.limit)+1
                if (curPage==1&&it.objects.size==0){
                    mView.fetchListEmpty("没有搜到相关信息，换个关键词看看吧")
                }else{
                    mExtras = it.extras
                    mView.onDoctorListFetched(it.objects, mExtras,curPage)
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    ToastUtil.toastShort(msg)
                    mView.fetchListFailed(msg)
                }
            })
    }
}