<template>
    <view class="bg-white">
        <u-dropdown ref="uDropdownRef" menu-icon="arrow-down-fill">
            <u-dropdown-item title="团队">
                <view class="bg-white">
                    <selectDropdown
                        ref="teamDropdownRef"
                        :dropdownItem="dropdownMenuTeamList"
                        :dropdownIndex="dropdownMenuTeamList.dropdownIndex"
                        @reset="() => handleReset('team')"
                        @confirm="
                            (value, dropdownIndex) => handleConfirm('team', value, dropdownIndex)
                        "
                    />
                </view>
            </u-dropdown-item>
            <u-dropdown-item title="组织">
                <view class="bg-white">
                    <selectDropdown
                        ref="orgDropdownRef"
                        :dropdownItem="dropdownMenuAllOrgaList"
                        :dropdownIndex="dropdownMenuAllOrgaList.dropdownIndex"
                        @reset="() => handleReset('organization')"
                        @confirm="
                            (value, dropdownIndex) =>
                                handleConfirm('organization', value, dropdownIndex)
                        "
                    />
                </view>
            </u-dropdown-item>
            <u-dropdown-item title="日期">
                <view class="bg-white p-[20rpx]">
                    <dateDropdownPicker
                        ref="dateDropdownPickerRef"
                        :dropdownItem="dropdownMenuDateList"
                        :dropdownIndex="dropdownMenuDateList.dropdownIndex"
                        @reset="() => handleReset('date')"
                        @confirm="
                            (value, dropdownIndex, dateTag) =>
                                handleConfirm('date', value, dropdownIndex, dateTag)
                        "
                    />
                </view>
            </u-dropdown-item>
        </u-dropdown>
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import selectDropdown from '@/components/select-dropdown/index.vue'
import dateDropdownPicker from '@/components/date-dropdown/daterange.vue'
import { formateDate, getCurDate } from '@/utils/util'
import { PropType } from 'vue'
import { IForm } from './team/index.vue'
import { computed } from 'vue'
import { apiOrganizationByIdList, apiOrganizationList, apiOrganizationTeamList } from '@/api/admin'

const props = defineProps({
    modelValue: {
        type: Object as PropType<IForm>,
        default: () => ({})
    }
})
const emit = defineEmits(['update:modelValue', 'refreshPage', 'confirm', 'reset'])

const dateDropdownPickerRef = ref<InstanceType<typeof dateDropdownPicker>>()
const teamDropdownRef = ref<InstanceType<typeof selectDropdown>>()
const orgDropdownRef = ref<InstanceType<typeof selectDropdown>>()
const uDropdownRef = ref()
const defaultValue = ref() //保存组织默认值
const organizationList = ref([])

const localValue = computed({
    get() {
        return props.modelValue
    },
    set(newValue) {
        return emit('update:modelValue', newValue)
    }
})
const dropdownMenuDateList = ref({
    dropdownIndex: 3,
    showQuick: true,
    title: '日期范围',
    type: 'daterange',
    prop: 'god6',
    value: { start: getCurDate('start', 'YYYY-MM-DD'), end: getCurDate('end', 'YYYY-MM-DD') }
})
const dropdownMenuTeamList = ref({
    dropdownIndex: 1,
    title: '下拉',
    type: 'cell',
    prop: 'god1',
    showAll: true,
    showIcon: true,
    options: []
})
const dropdownMenuAllOrgaList = ref({
    dropdownIndex: 2,
    title: '下拉',
    type: 'cell',
    prop: 'god1',
    showAll: true,
    showIcon: true,
    options: []
})
// 查询条件
const handleConfirm = (type: string, item, dropdownIndex?: number, dateTag?: string) => {
    switch (type) {
        case 'organization':
        case 'team':
            // 清空选择条件
            dropdownIndex == 1
                ? orgDropdownRef.value.clearSelect()
                : teamDropdownRef.value.clearSelect()
            localValue.value = {
                ...localValue.value,
                organizationId: item.value
            }
            break
        case 'date':
            localValue.value = {
                ...localValue.value,
                createTimeStart: formateDate(item.start, 'start'),
                createTimeEnd: formateDate(item.end, 'end')
            }
            break
        default:
            break
    }
    emit('refreshPage')
    emit('confirm', { dropdownIndex, dateTag })
    closeDropDown()
}
// 重置条件
const handleReset = (type: string) => {
    switch (type) {
        case 'organization':
        case 'team':
            localValue.value = {
                ...localValue.value,
                organizationId: defaultValue.value
            }
            break
        case 'date':
            localValue.value = {
                ...localValue.value,
                createTimeStart: getCurDate('start'),
                createTimeEnd: getCurDate('end')
            }
            break
        default:
            break
    }
    emit('refreshPage')
    emit('reset')
    closeDropDown()
}
const closeDropDown = () => {
    uDropdownRef.value.close()
}

// 获取主账号下的所有组织架构
const fetchOrganizationList = async () => {
    try {
        const result = await apiOrganizationList()
        organizationList.value = result ?? []
        if (result.length > 0) {
            localValue.value = {
                ...localValue.value,
                organizationId: result[0].id
            }
            defaultValue.value = result[0].id
        }
    } catch (error) {}
}
// 获取团队列表
const fetchTeamList = async () => {
    try {
        const result = await apiOrganizationTeamList()
        dropdownMenuTeamList.value.options =
            result.map(item => {
                return {
                    label: item.name,
                    value: item.id
                }
            }) ?? []
    } catch (error) {}
}
// 获取组织列表
const fetchAllOrganizationList = async () => {
    try {
        const result = await apiOrganizationByIdList()
        dropdownMenuAllOrgaList.value.options =
            result.map(item => {
                return {
                    label: item.name,
                    value: item.id
                }
            }) ?? []
    } catch (error) {}
}
// 传递参数赋值
const setDefaultValue = (dropdownIndex: string | number[], dateTag?: string) => {
    console.log(dropdownIndex)

    const dataMap: Record<number, any> = {
        '1': dropdownMenuTeamList,
        '2': dropdownMenuAllOrgaList,
        '3': dropdownMenuDateList
    }
    const arr = decodeURIComponent(dropdownIndex).split(',')
    arr.forEach(item => {
        if (
            item == dropdownMenuTeamList.value.dropdownIndex ||
            item == dropdownMenuAllOrgaList.value.dropdownIndex
        ) {
            dataMap[item].value.value = Number(localValue.value.organizationId)
        } else if (item == dropdownMenuDateList.value.dropdownIndex) {
            dropdownMenuDateList.value.value = {
                start: formateDate(localValue.value.createTimeStart, 'start', 'YYYY-MM-DD'),
                end: formateDate(localValue.value.createTimeEnd, 'end', 'YYYY-MM-DD')
            }
            dateDropdownPickerRef.value.initData(dropdownMenuDateList.value, false, dateTag)
        }
    })
}
fetchTeamList()
fetchAllOrganizationList()

defineExpose({
    setDefaultValue,
    fetchOrganizationList,
    defaultValue,
    organizationList
})
</script>
<style scoped></style>
