<template>
    <div class='ks-search'
        :class="className"
    >
        <div class='ks-search-box'>
            <div class="ks-search-left">
                <slot></slot>
            </div>
            <!-- 搜索部分 -->
            <div class="ks-search-right">
                <!-- 单条搜索的-->
                <KsInput 
                    v-if='searchType === "single"' 
                    class="ks-search-searchSingle"  
                    @onTransValue='onTransSingleValue'
                    :placeholder="placeholder"
                    ref='searchSingleInput'
                />
                <!-- 多条搜索的 -->
                <div v-if='searchType === "multiple"' class="ks-search-searchMulBox">
                    <Select
                        class="ks-search-searchMultiple"
                        v-model="searchKey"
                        @$change:value="onSearchChange"
                    >
                        <Option
                            v-for='item in _searchOptions'
                            :value='item.key'
                        >{{item.label}}</Option>
                    </Select>
                    <KsInput 
                        ref='searchMulInput'
                        class="ks-search-searchMoreInput"  
                        @onTransValue='onTransMulValue'
                        :placeholder="placeholder"
                    />
                </div>
                <div class='ks-search-btns' v-if='hasRefresh || hasDown'>
                    <span class="ks-search-span" v-if='hasRefresh'>
                        <Tooltip content="刷新" position='top'>
                            <Icon
                                class="k-icon-refresh"
                                size="16"
                                title="刷新"
                                @click="onRefresh"
                            />
                        </Tooltip>
                    </span>
                    <span class="ks-search-span" v-if='hasDown'>
                        <Tooltip content="下载" position='top'>
                            <Icon
                                class="k-icon-upload"
                                size="16"
                                title="下载"
                                @click="onExport"
                            />
                        </Tooltip>
                    </span>
                    <span class="ks-search-span" v-if='columnDatas.length'>
                        <Tooltip content="自定义列表" position='top'>
                            <Icon
                                class="k-icon-settings"
                                size="16"
                                title="自定义列表"
                                @click="onSetting"
                            />
                        </Tooltip>
                    </span>
                    <!-- 自定义列表配置逻辑 -->
                    <checkColumn :columnDatas="columnDatas" :columnKey='columnKey' @changeColumns="emit('changeColumns')"/>
                </div>
            </div>
        </div>
        <!-- 检索项 -->
        <div class='ks-search-retrievalBox' v-if='showRetrieval'> 
            <div class='ks-search-retrievalName'><span >检索项</span></div>
            <div class='ks-search-retrievalTags'>
                <ks-tag 
                    :dataList="_searchOptions"
                    @close="deleteSelectedData"
                />
                <Icon 
                    class='ks-search-tagdet k-icon-delete' 
                    @click='deleteAllData'
                    size='16'
                />
            </div>
        </div>
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { Icon, Input,Select, Option,Row, Col,Tooltip,Message,Dialog,Tip,Checkbox } from '@king-design/vue';
import KsTag from './tag.vue';
import KsInput from './input.vue'
import checkColumn from './checkColumn.vue';
import  {map,get,find,findIndex,forEach,isObject,} from 'lodash-es';
import {QueryChange} from "@ksconsole/hooks";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
const queryChange = new QueryChange(router,route)
const props = defineProps({
    searchOptions: { // 搜索条件的key值 和 label
        type: Array,
        default: []
    },
    noRetrieval: Boolean, // 是否有检索项
    columnDatas: { // 自定义列表数据，有就表示要展示相关按钮
        type: Array,
        default: []
    },
    onSearch: Function,
    hasDown: Boolean, // 是否有导出按钮
    hasRefresh: Boolean, // 是否有刷新按钮
    className: String,
    columnKey: String, // 自定义表头的唯一key值
});
// 接收父组件声明的方法
const emit = defineEmits(['refresh', 'onExport','onSearch','changeColumns'])
const sv = map(props.searchOptions,item=>({ ...item, value:''}))
const _searchOptions = ref(sv)
// searchType = single 单个搜索条件 multiple 多个搜索条件 
const searchType = ref(_searchOptions.value.length === 1 ? 'single' : (_searchOptions.value.length > 1 ? 'multiple' : '') )
const defalutOption = get(_searchOptions.value,[0],[])
// const placeholder = ref(defalutOption.label)
const placeholder = ref(defalutOption.placeholder || `请输入${defalutOption.label}`)

// 单个搜索逻辑 start
const searchSingleInput = ref(null)
const onTransSingleValue = (val) => {
     emit('onSearch',{[defalutOption.key]:val})
     _searchOptions.value[0].value = val 
}
// 单个搜索逻辑 end

// 多个搜索条件组合时候的逻辑-start
const searchMulInput = ref(null)
const showRetrieval = ref(false)
const searchKey = ref(defalutOption.key)

const onSearchChange = (value) => {
    searchKey.value = value
    searchMulInput.value.onChange('')
    // placeholder.value = get(find(_searchOptions.value,['key',value]),'label','')
    const currentInfo = find(_searchOptions.value,['key',value])
    placeholder.value = currentInfo.placeholder || '请输入' + get(currentInfo,'label','')
}
const optionToggle = () => {
    let data = getnewData()
    if(props.noRetrieval) { // 没有检索项时候，多条的选择也只传递当前的搜索结果
        data = { [searchKey.value]: get(_searchOptions.value,[findIndex(_searchOptions.value,['key',searchKey.value]),'value']) }
    }
    emit('onSearch',data)
}

const onTransMulValue = (val) => {
    const index = findIndex(_searchOptions.value,['key',searchKey.value]);
    _searchOptions.value[index].value = val 
    // 判断 检索项是否还存在，只要有值就存在
    isShowRetrieval()
}

// 单个删除tag时候，清空当前key的value
const deleteSelectedData = (item) => {
    _searchOptions.value = map(_searchOptions.value,option => 
        option.key === item.key ? { ...option, value: '' } : option
    );
    // 判断 检索项是否还存在，只要有值就存在
    isShowRetrieval()
}
// 删除所有检索
const deleteAllData = () => {
    _searchOptions.value = map(_searchOptions.value,option =>({ ...option, value: '' }));
    // 判断 检索项是否还存在，只要有值就存在
    isShowRetrieval()
}

const isShowRetrieval = () => {
    // 判断 检索项是否还存在，只要有值就存在
    if(props.noRetrieval) {
        showRetrieval.value = false
    }else {
        showRetrieval.value = _searchOptions.value.some(item => item.value);
    }
    optionToggle()
}
// 多个搜索条件组合时候的逻辑-end

// 刷新 
const onRefresh = () => {
    let obj = {}
    if(searchType.value === 'single') { // 单条搜索
        const info = get(_searchOptions.value,[0],{})
        obj[info.key] = info.value
    }else if(searchType.value === 'multiple'){ // 多条搜索
        obj = {...getnewData()}
    }
    emit('onSearch',obj)
    Message.success('刷新成功')
}

const getnewData = (data={}) => {
    forEach(_searchOptions.value,item=>{
        if(item.value){
            data[item.key] = item.value
        }
    })
    return data
}
// 重置查询条件
const _reset = () => {
    if(searchType.value === "multiple"){
        // 1. 去除搜索框的内容
        // 2. 去除检索项的内容
        searchMulInput.value.onChange('')
        // 3. 去除 查询条件里的value的值
        _searchOptions.value = map(_searchOptions.value,option =>({ ...option, value: '' }));
        // 4. 隐藏检索项
        showRetrieval.value = false
    }else {
        searchSingleInput.value.onChange('')
    }
}

const onSetting = () => {
    queryChange._toDetails('','setting')
}


const onExport = () => {
    // 触发父组件方法
    emit('onExport')
}

defineExpose({
    _reset
})
</script>

<style scoped lang="less">
.ks-search {
    margin-bottom: 16px;
    .ks-search-box {
        display: flex;
        justify-content: space-between;
        background: #fff;
    }
    .ks-search-span {
        display: inline-block;
        width: 24px;
        text-align: center;
        line-height: 24px;
        height: 24px;
        margin-left: 8px;
        i {
            cursor: pointer;
        }
        &:hover {
            i {
                color: #1890FE;
            }
        }
    }

    .ks-search-left {
        display: flex;
        align-items: center;
    }
    .ks-search-right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        flex: 2;
        & > .k-icon {
            margin-left: 10px;
        }
    }
     .ks-search-searchSingle {
        width: 240px;
        height: 32px;
    }
    .ks-search-searchMulBox {
        min-width: 363px;
    }
    .ks-search-searchMultiple {
        width: 120px;
        height: 32px;
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
    }
    .ks-search-searchMoreInput {
        width: 240px;
    }
    .ks-search-searchMoreInput :deep(.k-input-wrapper) {
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
    }
    .ks-search-refresh {
        &::hover {
            color: #1890FE;
        }
    }
    .ks-search-retrievalBox {
        padding: 16px 0px 0px 0px;
        display: flex;
    }
    .ks-search-retrievalName {
        flex: 0 0 38px;
        font-size: 12px;
        margin-right: 16px;
        position: relative;
        top: 3px;
    }
    .ks-search-retrievalTags {
        flex: auto;
    }

    .ks-search-tagdet {
        padding-left: 6px;
        position: relative;
        top: 2px;
        cursor: pointer;
    }
}
</style>
