<template>
    <view>
        <z-paging ref="paging" v-model="projectList" @query="queryList" :default-page-size="detaultPageSize" empty-view-text="暂无项目数据"
            :back-to-top-style="{ right: '44rpx' }" back-to-top-bottom="170rpx" :show-scrollbar="false"
            :auto-show-back-to-top="true">
            <template #top>
                <view>
                    <custom-dropdown ref="dropdownRef" :dropdownMenu="dropdownMenuList" themeColor="#007aff"
                        style="width:100%;border-top: 1px solid #edf0f9;" textColor="#333333" :duration="300"
                        @confirm="handleConfirm" @close="handleClose" bgColor="#f8f8f8" @open="handleOpen">
                        <template #slot1="{ item, index }">
                            <view style="width: 100%;height: 300px;">
                                <next-tree ref="regionTreeRef" :ifSearch="true" :showDropdownFooter="true"
                                    :showAuxiliaryLine="false" :border="true" labelKey="name" :showBottomBar="true"
                                    :checkStrictly="true" :selectParent="true" funcMode="radio"
                                    :treeData="regionTreeData" uiMode="page" @confirm="confirmRegion">
                                </next-tree>
                            </view>
                        </template>
                    </custom-dropdown>
                </view>
            </template>
            <List :project-list="projectList" :prj-phase-list="prjPhaseList" />
        </z-paging>
        <uni-fab  :content="[]" :popMenu="false" horizontal="right" :showFabBtn="true" direction="bottom"
            @fabClick="redierectProjectPage" />
    </view>
</template>
<script lang="ts" setup>
import customDropdown from '@/components/cu-dropdown/index.vue'
import List from './List.vue'
import nextTree from '@/components/next-tree/next-tree.vue'
import { DomainTree } from '@/types/domain';
import { Project } from '@/types/project';
import { getProjectList } from '@/api/project-center/info';
import { getPrjPhaseList, getPrjTypeList } from '@/api/base/base';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { useUserStore } from '@/stores';
import { getPermissions } from '@/api/base/client';
import { getRegionTree } from '@/api/base/region';

const paging = ref()
const regionTreeRef = ref()
const detaultPageSize = 10;
const projectList = ref<Project[]>([])
const dropdownRef = ref()
const prjPhaseList = ref<{ id: string; name: string; color: string }[]>([])
const regionTreeData = ref<DomainTree[]>([]) // 区域树

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
    name?: string
    type_id?: string
    region_id?: number
    phase_id?: string
    deliver_at?: string[]
}>({
    name: undefined,
    type_id: undefined,
    region_id: undefined,
    phase_id: undefined,
    deliver_at: undefined
})

const getPrjPhase = async () => {
    const { list } = await getPrjPhaseList()
    prjPhaseList.value = list
    return list.map(item => { return { label: item.name, value: item.id } })
}

const getType = async () => {
    const { tree } = await getPrjTypeList()
    return tree
}



const dropdownMenuList = ref([
    {
        title: '项目名称',
        type: 'search',
        prop: 'name',
        placeholder: '按项目名称搜索'
    },
    {
        title: '所属地区',
        type: 'slot1',
        prop: 'region_id',
        showArrow: true,
        showIcon: true,
    },
    {
        title: '项目类型',
        type: 'picker',
        prop: 'type_id',
        showAll: true,
        showIcon: true,
        field: {
            label: 'name',
            value: 'id',
            children: 'children',
        },

        options: [],
        // syncDataFn: getType
    },
    {
        title: '项目阶段',
        type: 'filter',
        prop: 'phase',
        showAll: true,
        showIcon: true,
        options: [],
    },
    {

        title: '预计交付',
        showAll: true,
        showIcon: true,
        type: 'daterange',
        prop: 'deliver_at',
        // 默认选中 2022-01-01到2022-02-01
        // value: { start: '2022-01-01', end: '2022-02-01' },
    },
])


/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
    const {
        name,
        type_id,
        region_id,
        phase_id,
        deliver_at
    } = filterForm
    const deliver_at_from = deliver_at ? deliver_at[0] : deliver_at
    const deliver_at_to = deliver_at ? deliver_at[1] : deliver_at
    return {
        name,
        type_id,
        region_id,
        deliver_at_from,
        deliver_at_to,
        phase_id
    }
}

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = async (pageNo: number, pageSize: number) => {
    try {
        const { name, type_id, region_id, deliver_at_from, deliver_at_to, phase_id } = getFilterForm()
        const params = { page_no: pageNo, page_size: pageSize, name, type_id, region_id, deliver_at_from, deliver_at_to, phase_id }
        const { list } = await getProjectList(params)
        nextTick(() => {
            paging.value?.complete(list);
        })
    } catch (e) {
        paging.value?.complete(false);
    }
}

/**
 * 获取区域树
 */
const getTree = async () => {
    const { tree } = await getRegionTree()
    regionTreeData.value = tree
}

function handleConfirm(v: any) {
    console.log('handleConfirm ==>', v)
    const dropdownValues = dropdownRef.value?.getMenuValue()
    filterForm.region_id = dropdownValues.region_id
    filterForm.name = dropdownValues.name
    filterForm.type_id = dropdownValues.type_id ? dropdownValues.type_id[dropdownValues.type_id.length - 1] : dropdownValues.type_id
    filterForm.phase_id = dropdownValues.phase ? dropdownValues.phase.id : dropdownValues.phase
    filterForm.deliver_at = dropdownValues.deliver_at ? [dropdownValues.deliver_at.start, dropdownValues.deliver_at.end] : dropdownValues.deliver_at
    paging.value?.reload()
}


function handleClose(index: number) {
    console.log('handleClose ==>', index)
}

const confirmRegion = (v: any) => {
    if (v.length > 0) {
        dropdownRef.value?.updateMenu('region_id', v[0].id, 'value')
        dropdownRef.value?.updateMenu('region_id', true, 'isActived')
    } else {
        dropdownRef.value?.updateMenu('region_id', undefined, 'value')
        dropdownRef.value?.updateMenu('region_id', false, 'isActived')
    }
    dropdownRef.value?.closeMenuPopup()
    handleConfirm(1)
}

async function handleOpen(index: number) {
    console.log('handleOpen ==>', index)
}


const redierectProjectPage = () => {
    console.log('点击跳转到添加项目页面')
    uni.navigateTo({ url: '/pages/project/components/add-project' })
}

async function initDropMenData() {
    const options = await getPrjPhase()
    dropdownRef.value?.updateMenu('phase', [{
        title: '',
        type: 'radio',
        prop: 'id',
        options,
    }], 'options')
    const type = await getType()
    dropdownRef.value?.updateMenu('type_id', [{ name: '不限', id: '-9999' }, ...type], 'options')

}


// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
    name: 'get_project_list',
    callback: () => {
        paging.value?.reload()
    }
})



// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
    name: 'remove_project',
    callback: (id: string) => {
        projectList.value = projectList.value.filter(item => item.id !== id)
        uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500
        })
    }
})

const getPlist = async () => {
    const userStore = useUserStore()
    const { list } = await getPermissions();
    userStore.setPermissionsList(list)
}

onMounted(() => {
    getTree()
    initDropMenData()
    getPlist()
})

</script>

<script lang="ts">
export default {
    options: {
        styleIsolation: 'apply-shared', //解除样式隔离
    }

}
</script>
<style scoped lang="scss">
.grid-container {
    margin: 0 !important;
}

.grid-item-box {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
    background-color: #f8f8f8;
}

.c-nav-bar {
    &__content {
        color: red;
    }
}

.is-hover {
    color: rgba(255, 255, 255, 0.6);
    background-color: #179b16;
    border-color: #179b16;
}

.city {
    /* #ifndef APP-PLUS-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    margin-left: 4px;
}

.box-bg {
    background-color: #F5F5F5;
}


.input-view {
    /* #ifndef APP-PLUS-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    flex: 1;
    // background-color: #f8f8f8;
    // height: 30px;
    // border-radius: 15px;
    flex-wrap: nowrap;
    margin: 7px 3px 7px 0px;
    // padding-left: 4px;
    line-height: 30px;
}

.input-uni-icon {
    line-height: 30px;
}

.nav-bar-input {
    height: 30px;
    line-height: 30px;
    /* #ifdef APP-PLUS-NVUE */
    /* #endif */
    padding: 0 5px;
    font-size: 12px;
    background-color: #f8f8f8;
}

:deep(.uni-searchbar__box-icon-clear) {
    padding-top: 5px;
}

.uni-navbar {
    &__header {
        padding: 0 !important
    }
}

:deep(.uni-searchbar) {
    padding: 0;
    width: 100%
}

:deep(.uni-searchbar__box) {
    height: 30px !important;
}

:deep(.uni-navbar__header-container) {
    padding: 0px !important;
}


:deep(.uni-searchbar__cancel) {
    height: 30px;
    line-height: 30px;
}
</style>