<template>
    <hc-sys id="app-sys" class="hc-images-page" :isNavBar="false">
        <view id="hc-images-nav-bar" class="hc-images-nav-bar" un-border-b="1 solid gray-2">
            <hc-nav-back-bar title="声像文件">
                <view class="more-bar" v-if="dataList.length > 0" @click="deleteTap">
                    <text class="text-26" :class="isDelete?'':'text-red-4'">{{isDelete? '取消' : '删除'}}</text>
                </view>
            </hc-nav-back-bar>
            <view class="cu-bar bg-white search py-2" un-border-t="1 solid gray-2" v-if="pageNode.type === 1">
                <view class="search-form radius">
                    <text class="cuIcon-search"/>
                    <input v-model="searchForm.queryStr" :adjust-position="false" type="text" placeholder="根据题名，名称或拍摄者搜索" confirm-type="search"/>
                </view>
                <view class="action">
                    <button class="cu-btn bg-blue-5 text-white" hover-class="none" @click="searchClick">搜索</button>
                </view>
            </view>
            <view class="cu-bar bg-white search py-2" un-border-t="1 solid gray-2" v-if="pageNode.type === 2">
                <view class="search-form radius">
                    <uni-datetime-picker type="date" v-model="searchForm.queryDate"/>
                </view>
                <view class="action">
                    <button class="cu-btn bg-blue-5 text-white" hover-class="none" @click="searchClick">搜索</button>
                </view>
            </view>
        </view>

        <!-- 数据列表 -->
        <z-paging ref="pageRef" :style="pagingStyle" v-model="dataList" @query="getDataList">
            <template v-for="(item, index) in imageList" :key="index">
                <view class="cu-bar bg-white py-2 mt-1" un-border-b="1 solid gray-1">
                    <view class="px-3">{{item.name}}</view>
                </view>
                <template v-for="(items, indexs) in item.child" :key="indexs">
                    <view class="bg-white hc-p hc-flex" un-border-b="1 solid gray-1" @click="itemClick(items, index, indexs)">
                        <view class="hc-flex mr-2" v-if="isDelete" @click.stop="checkClick(items, index, indexs)">
                            <uni-icons type="checkbox-filled" size="26" color="#ee5b20" v-if="items.check"/>
                            <uni-icons type="checkbox" size="26" color="#9a9a9a" v-else/>
                        </view>
                        <view class="hc-flex">
                            <view class="hc-flex-center h-100 w-100 b-rounded" un-border="1 solid gray-3" v-if="items.type === 1">
                                <text class="i-ri-vidicon-line text-50 text-gray-4"/>
                            </view>
                            <hc-img class="b-rounded" :src="items.imageUrl?.toString()?.split(',')[0]" width="50" height="50" v-if="items.type === 2"/>
                        </view>
                        <view class="relative flex-1 ml-3">
                            <view class="text-30 text-black clip-2">{{items.title}}</view>
                            <view class="text-24 mt-1 text-cut">{{items.textContent}}</view>
                        </view>
                    </view>
                </template>
            </template>
        </z-paging>

        <!--底部操作区域 -->
        <view id="hc-bottom-bar" class="hc-bottom-bar"/>
        <view id="hc-bottom-btn-bar" class="hc-bottom-btn-bar">
            <view class="hc-flex" v-if="isDelete">
                <view class="hc-flex" @click="allCheckClick">
                    <uni-icons type="checkbox-filled" size="24" color="#ee5b20" v-if="checkList.length === dataList.length"/>
                    <uni-icons type="checkbox" size="24" color="#9a9a9a" v-else/>
                    <text class="ml-1">全选</text>
                </view>
                <view class="flex-1 ml-4 text-gray-5 text-24">
                    <text class="mr-1">已勾选</text>
                    <text class="text-red-5">{{checkList.length}}</text>
                    <text class="ml-1">条数据</text>
                </view>
                <button hover-class="none" class="cu-btn bg-red-5 text-white" @click="delCheckList">删除选中</button>
            </view>
            <view class="relative" v-else>
                <button hover-class="none" class="cu-btn block bg-purple-8 text-white" @click="addFileData">新增声像文件</button>
            </view>
        </view>
    </hc-sys>
</template>

<script setup>
import {getCurrentInstance, ref} from "vue";
import {onLoad, onShow, onReady} from '@dcloudio/uni-app'
import {useAppStore} from "@/store";
import mainApi from '~api/image/index';
import {arrIndex, deepClone, getArrValue} from "js-fast-way";
import {errorToast, querySelect, showModal, successToast} from "@/utils/tools";

//初始变量
const store = useAppStore()
const instance = getCurrentInstance().proxy
const contractInfo = ref(store.contractInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);

//基础变量
const pageRef = ref(null)
const pageNode = ref({});
const dataList = ref([])
const isNodes = ref(false)

//页面启动
onLoad(({node}) => {
    pageNode.value = node ? JSON.parse(decodeURIComponent(node)) : {};
})

onReady(() => {
    setPagingStyle()
})

onShow(() => {
    if (isNodes.value) {
        searchClick()
    }
})

//内容区域
const pagingStyle = ref({
    position: 'relative',
    width: '100%',
    bottom: 0,
})
const setPagingStyle = async () => {
    const {height: appHeight} = await querySelect(instance, 'app-sys')
    const {height: navHeight} = await querySelect(instance, 'hc-images-nav-bar')
    const {height: bottomHeight} = await querySelect(instance, 'hc-bottom-bar')
    const {height: bottomBtnHeight} = await querySelect(instance, 'hc-bottom-btn-bar')
    // #ifdef H5
    let content = navHeight + bottomHeight + bottomBtnHeight
    pagingStyle.value.height = (appHeight - content) + 'px'
    // #endif
    // #ifdef APP-PLUS
    const {screenHeight, safeArea} = uni.getWindowInfo()
    content = navHeight + (screenHeight - safeArea.bottom) + bottomBtnHeight
    pagingStyle.value.height = (screenHeight - content) + 'px'
    // #endif
}

//条件搜索
const searchClick = () => {
    imageList.value = []
    pageRef.value?.reload()
}

//获取数据
const searchForm = ref({queryStr: ''})
const getDataList = async (pageNo, pageSize) => {
    if (pageNo === 1) {
        imageList.value = []
    }
    const {id, fileType, type, treeId} = pageNode.value
    if (!type || !id || !type || !fileType) {
        errorToast('参数异常，请退出重试')
        pageRef.value?.complete([]);
        return false;
    }
    //树类型
    const form = searchForm.value
    if (type === 1 && treeId) {
        delete form.queryDate
        form.wbsIdsStr = treeId
    }
    if (type === 2) {
        delete form.wbsIdsStr
        delete form.queryStr
    }
    //获取数据
    uni.showLoading({title: '获取数据中...', mask: true});
    const { data } = await mainApi.getPageList({
        ...form,
        projectId: projectId.value,
        contractId: contractId.value,
        classifyId: id,
        current: pageNo,
        size: pageSize,
        isApp: 1,
    })
    //处理数据
    let res = getArrValue(data), newArr = [];
    if (res.length > 0) {
        for (let i = 0; i < res.length; i++) {
            const item = res[i].child;
            for (let j = 0; j < item.length; j++) {
                newArr.push(item[j])
            }
        }
        setImageList(deepClone(res)) //处理数据
        pageRef.value?.complete(newArr);
    } else {
        pageRef.value?.complete([]);
    }
    isNodes.value = true
    uni.hideLoading();
}

//处理列表显示数据
const imageList = ref([])
const setImageList = (data) => {
    const arr = imageList.value
    if (arr.length > 0 && data.length > 0) {
        const item = arr[arr.length - 1]
        const items = data[0]
        if (item.name === items.name) {
            const child = item.child
            item.child = child.concat(items.child)
            data.splice(0, 1)
        }
        imageList.value = arr.concat(data)
    } else {
        imageList.value = data
    }
}

//批量删除
const isDelete = ref(false)
const deleteTap = () => {
    isDelete.value = !isDelete.value
}

//点击选中
const checkList = ref([])
const checkClick = (item) => {
    const list = checkList.value
    const index = arrIndex(list, 'id', item.id)
    if (item.check) {
        list.splice(index, 1)
        item.check = false
    } else {
        item.check = true
        list.push(item)
    }
    checkList.value = list
}

//全选
const allCheckClick = () => {
    const check = checkList.value, list = dataList.value
    const arr = imageList.value
    if (check.length === list.length) {
        arr.forEach(item => {
            item.child.forEach(items => {
                items.check = false
            })
        })
        checkList.value = []
    } else {
        let newArr = []
        arr.forEach(item => {
            item.child.forEach(items => {
                items.check = true
                newArr.push(items)
            })
        })
        checkList.value = newArr
    }
}

//列表项被点击
const itemClick = (item, index, indexs) => {
    if(isDelete.value) {
        checkClick(item, index, indexs)
    } else {
        uni.navigateTo({
            url: `/pages/image/info?id=${item.id}`
        })
    }
}

//删除选中数据
const delCheckList = async () => {
    if (checkList.value.length <= 0) {
        errorToast('请选择要删除的数据')
        return false
    }
    const res = await showModal({
        title: '批量删除提醒',
        content: '确定要删除选中的数据吗？',
    })
    if (!res) return false;
    uni.showLoading({title: '批量删除中...', mask: true});
    const ids = checkList.value.map(item => item.id)
    const { error, code, msg } = await mainApi.removeImageclassifyFile({
        ids: ids.join(',')
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('删除成功')
        searchClick()
    } else {
        errorToast('删除失败: ' + msg)
    }
}

//新增文件数据
const addFileData = () => {
    //准备跳转路由
    const node = encodeURIComponent(JSON.stringify({
        ...pageNode.value
    }));
    uni.navigateTo({
        url: `/pages/image/form?node=${node}`
    })
}
</script>

<style lang="scss">
@import "@/style/image/view.scss";
</style>
