<template>
    <view class="container">
        <z-paging ref="paging" v-model="docList" @query="queryList" :back-to-top-style="{ right: '44rpx' }" empty-view-text="暂无文档数据"
            :paging-style="{ top: isDetail ? '39px' : '' }" back-to-top-bottom="170rpx" :show-scrollbar="false"
            :default-page-size="detaultPageSize" :safe-area-inset-bottom="true">
            <template #top>
                <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 :ifSearch="true" :showDropdownFooter="true" :showAuxiliaryLine="false"
                                :border="true" labelKey="name" :showBottomBar="true" :checkStrictly="true"
                                :selectParent="true" funcMode="radio" :treeData="prjList" uiMode="page"
                                @confirm="confirmProject">
                            </next-tree>
                        </view>
                    </template>
                    <template #slot2="{ item, index }">
                        <view style="margin: 40rpx 40rpx 0">
                            <uni-easyinput prefixIcon="search" v-model="filename" placeholder="按名称模糊查询"
                                @clear="resetFilename">
                            </uni-easyinput>
                            <PartDropdownFooter @reset="resetFilename" @confirm="confirmFilename" />
                        </view>
                    </template>
                </custom-dropdown>
            </template>
            <List :doc-list="docList" :archived="props.archived" />
            <template #bottom v-if="allowUpload">
                <view style="padding: 0 10px;position: relative;bottom: 1px;">
                    <uni-file-picker v-if="!showUploadProgress" file-mediatype="all" :auto-upload="false" :limit="1" ref="upload_picker"
                        mode="list" :list-styles="{ display: 'none' }" @select="(e: any) => handlerSelectFileUpload(e)"
                        :del-icon="false">
                        <view>
                            <custom-button width="100%" color="#007aff" :radius="['5px']" @click.prevent=""
                                ripple>上传文件</custom-button>
                        </view>
                    </uni-file-picker>
                    <view v-else
                        style="height: 100%;background: #fff;display: flex;padding: 10px 5px;align-items: center;border-radius: 5px;">
                        <custom-progress v-model:value="uploadrogress" :stroke-width="16" min-width="150px"
                            style="width:100%"></custom-progress>
                    </view>
                </view>
            </template>
        </z-paging>
    </view>
</template>


<script lang="ts" setup>
import customDropdown from '@/components/cu-dropdown/index.vue'
import PartDropdownFooter from '@/components/cu-dropdown/components/part-dropdown-footer.vue'
import nextTree from '@/components/next-tree/next-tree.vue'
import List from './document-list.vue'
import { getDocTypeList } from '@/api/base/base';
import { PrjDocument } from '@/types/document';
import { getDocumentList, getUploadDocumentUrl } from '@/api/project-center/document';
import { uploadFile } from '@/api/base/client';
import customProgress from '@/components/cu-progress/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt';


const upload_picker = ref()
const detaultPageSize = 10;
const paging = ref()
const docList = ref<PrjDocument[]>([])
const dropdownRef = ref()
const filename = ref()
const showUploadProgress = ref(false)
const uploadrogress = ref(0)


const props = defineProps({
    prj_id: {
        type: String
    },
    isDetail: {
        type: Boolean,
        required: false
    },
    hiddenPrFilterItem: {
        type: Boolean,
        required: false
    },
    hiddenCategoryFilterItem: {
        type: Boolean,
        required: false
    },
    prjList: {
        type: Array as PropType<{ id: string; name: string }[]>
    },
    archived: {
        type: Boolean,
        default: () => {
            return undefined
        }
    },
})

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
    prj_id?: string
    date?: string[]
    filename?: string
    category_id?: string
}>({
    prj_id: props.prj_id,
    filename: undefined,
    date: undefined,
    category_id: undefined
})


const categories = ref<
    {
        id: string
        name: string
        color: string
        allow_upload: boolean
    }[]
>([])

const resetFilename = () => {
    filename.value = undefined
}

const dropdownMenuList = ref([
    {
        title: '所属项目',
        type: 'slot1',
        prop: 'prj_id',
        showArrow: true,
        showIcon: true,
        value: props.prj_id,
        hidden: props.hiddenPrFilterItem,
    },
    {
        title: '文档分类',
        type: 'cell',
        prop: 'category_id',
        showAll: true,
        showIcon: true,
        hidden: props.hiddenCategoryFilterItem,
        field: {
            label: 'name',
            value: 'id'
        },
        options: []
    },
    {
        title: '文件名称',
        type: 'slot2',
        prop: 'filename',
        showArrow: true,
        showIcon: true,
    },
    {

        title: '上传时间',
        showAll: true,
        showIcon: true,
        type: 'daterange',
        prop: 'date'
    },
])

const activeIndex = ref()


const getType = async () => {
    const { list } = await getDocTypeList()
    categories.value = list
    if (list.length > 0) {
        activeIndex.value = list[0].id
    }
}


const allowUpload = computed(() => {
    return categories.value.find(item => item.id === filterForm.category_id)?.allow_upload && !props.archived
})
/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
    const {
        prj_id,
        date,
        filename,
        category_id
    } = filterForm
    const begin_from = date ? date[0] : date
    const end_to = date ? date[1] : date
    return {
        archived: props.archived,
        prj_id,
        filename,
        begin_from,
        end_to,
        category_id
    }
}

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = async (pageNo: number, pageSize: number) => {
    try {
        const { filename, begin_from, end_to, category_id, prj_id, archived } = getFilterForm()
        const { list } = await getDocumentList({
            page_no: pageNo, page_size: pageSize, prj_id, filename, begin_from, end_to, category_id, archived
        })
        paging.value?.complete(list);
    } catch (e) {
        paging.value.complete(false);
    }
}

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

const confirmFilename = () => {
    if (![undefined, null, ''].includes(filename.value)) {
        dropdownRef.value?.updateMenu('filename', filename.value, 'value')
        dropdownRef.value?.updateMenu('filename', true, 'isActived')
    } else {
        dropdownRef.value?.updateMenu('filename', undefined, 'value')
        dropdownRef.value?.updateMenu('filename', false, 'isActived')
    }
    dropdownRef.value?.closeMenuPopup()
    handleConfirm(3)
}

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

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

}

function handleConfirm(v: any) {
    console.log('handleConfirm ==>', v)
    const dropdownValues = dropdownRef.value?.getMenuValue()
    if (!props.prj_id) {
        filterForm.prj_id = dropdownValues.prj_id
    }
    filterForm.filename = dropdownValues.filename;
    filterForm.category_id = dropdownValues.category_id;
    filterForm.date = dropdownValues.date ? [dropdownValues.date.start, dropdownValues.date.end] : dropdownValues.date
    paging.value?.reload()
}

// 监听上传进度条
const onUploadProgressResult = (e: UniApp.OnProgressUpdateResult) => {
    showUploadProgress.value = true
    uploadrogress.value = e.progress
}


// 选择文件上传
const handlerSelectFileUpload = async (e: {
    tempFilePaths: string[], tempFiles: {
        name: string
        extname: string
        url: string
    }[]
}) => {
    try {
        const { tempFiles, tempFilePaths } = e
        if (tempFilePaths.length > 0) {
            const { url, form_data, headers, object_name } = await getUploadDocumentUrl({
                prj_id: filterForm.prj_id!,
                category_id: filterForm.category_id!,
                filename: tempFiles[0].name
            })
            await uploadFile({ url, object_name, headers, formData: form_data, filePath: tempFilePaths[0], uploadProgress: onUploadProgressResult })
            uni.showToast({
                icon: 'success',
                title: '上传成功'
            })
            showUploadProgress.value = false
            uploadrogress.value = 0
            upload_picker.value?.clearFiles()
            paging.value?.reload()
        }
    } catch (_e) {
        showUploadProgress.value = false
        uploadrogress.value = 0
        upload_picker.value?.clearFiles()
    }

}

async function initDropMenData() {
    if (!props.hiddenCategoryFilterItem) {
        await getType()
        nextTick(() => {
            dropdownRef.value?.updateMenu('category_id', [{ name: '不限', id: '-9999' }, ...categories.value], 'options')
        })
    }
}

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


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


</script>
<script lang="ts">


export default {
    // shared:表示页面 wxss 样式将影响到自定义组件
    options: {
        styleIsolation: 'shared'
    }
};
</script>

<style lang="scss" scoped>
.flex-row {
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.container {
    .content-wrap {

        // padding-left: 24rpx;
        .title-wrap {
            padding: 5px
        }
    }

}

::v-deep .y-tabs {
    height: 100% !important;

    // 滑块
    &__bar.is-vertical.is-line {
        left: 0 !important;
    }

    // 滑块内容
    &__bar-inner {
        border-radius: 0 !important;
    }

    .y-tabs__nav {
        background: #fff;
    }

    .y-tab {
        height: 44px;
        background-color: #f7f7f7;

        &.first-tab {
            .y-tab__image {
                position: absolute;
                top: 14px;
                right: 10px;
            }
        }

        // 标签选中态
        &.is-active {
            background-color: #fff;
        }

        &__prev {
            border-bottom-right-radius: 6px;
        }

        &__next {
            border-top-right-radius: 6px;
        }

        // 图片
        &__image {
            width: 32rpx;
            height: 32rpx;
            border-radius: 50%;
            margin-right: 4rpx;
        }
    }
}
</style>