<template>
    <div class="hc-layout-box">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'">
            <template v-if="dataType === 1">
                <div class="hc-project-box">
                    <div class="hc-project-icon-box">
                        <HcIcon name="layers"/>
                    </div>
                    <div class="ml-2 project-name-box">
                        <span class="text-xl text-cut project-alias">{{projectInfo['projectAlias']}}</span>
                        <div class="text-xs text-cut project-name">{{projectInfo['name']}}</div>
                    </div>
                </div>
                <div class="hc-tree-box">
                    <el-scrollbar>
                        <WbsTree :autoExpandKeys="TreeAutoExpandKeys" :projectId="projectId" :contractId="contractId" @nodeTap="nodeWbsElTreeClick"/>
                    </el-scrollbar>
                </div>
            </template>
            <div class="hc-tree-box date-tree" v-else>
                <el-scrollbar>
                    <HcTreeData :datas="dateElTreeData" :autoExpandKeys="TreeExpandedKeys" @nodeTap="dateWbsElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-layout-content-box">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="image-data-add">
                        <el-button type="primary" hc-btn :disabled="!queryKey && fileType === 1" @click="addFormFile">
                            <HcIcon name="add_box"/>
                            <span>新增文件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="image-data-download">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="downloadLoading" @click="downloadClick">
                            <HcIcon name="download"/>
                            <span>下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="image-data-del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="delLoading" @click="delClick">
                            <HcIcon name="delete"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <div class="w-60">
                        <el-input v-model="searchForm.queryStr" size="large" placeholder="根据题名名称或拍摄者搜索" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" size="large" @click="searchClick">搜索</el-button>
                    </div>
                </template>
                <HcTable ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading" isCheck @selection-change="tableSelectionChange">
                    <template #info="{row}">
                        <div class="hc-table-col-item">
                            <div class="img-box" v-if="row.type !== 1">
                                <HcImg class="hc-image" :src="setImageUrl(row.imageUrl)"/>
                            </div>
                            <div class="img-box" v-else>
                                <video :src="row.imageUrl">
                                    您的浏览器不支持 video
                                </video>
                            </div>
                            <div class="content-box">
                                <div class="text-cut title">{{row.title}}</div>
                                <div class="shootingUser">拍摄者：{{row.shootingUser}}</div>
                                <div class="shootingTimeStr">拍摄时间：{{row.shootingTimeStr}}</div>
                                <div class="fileSize">文件大小：{{row.fileSize}}</div>
                            </div>
                        </div>
                    </template>
                    <template #operate="{row}">
                        <HcTooltip keys="image-data-preview">
                            <el-button type="primary" size="small" text @click="previewClick(row)">查看</el-button>
                        </HcTooltip>
                        <HcTooltip keys="image-data-edit">
                            <el-button type="primary" size="small" text @click="editClick(row)">编辑</el-button>
                        </HcTooltip>
                    </template>
                </HcTable>
                <template #action>
                    <div class="lr-dialog-footer">
                        <div class="left">
                            <el-button size="large" @click="goToBack">返回上级</el-button>
                        </div>
                        <div class="right">
                            <HcPages :pages="searchForm" @change="pageChange"/>
                        </div>
                    </div>
                </template>
            </HcCard>
        </div>
        <!--视频预览 弹框-->
        <el-dialog v-model="previewVideoModal" title="预览" width="47rem" destroy-on-close custom-class="hc-modal-border">
            <video class="preview-video" :src="previewVideoUrl" controls="controls" autoplay="autoplay" v-if="previewVideoUrl">
                您的浏览器不支持 video
            </video>
        </el-dialog>
    </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import {useAppStore} from "~src/store";
import {useRouter, useRoute} from 'vue-router'
import WbsTree from "./components/WbsTree.vue"
import HcTreeData from "./components/HcTreeData.vue"
import imageApi from '~api/other-file/imageData';
import {getStoreData, setStoreData} from '~src/utils/storage'
import {downloadBlob, getArrValue, getObjNullValue} from "vue-utils-plus"

//变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const isCollapse = ref(useAppState.getCollapse)

//路由参数
const routerQuery = useRoutes?.query;
//存储目录格式 1按部位存储，2按日期存储
const dataId = routerQuery?.id || '';
const dataType = parseInt(routerQuery?.type + '') || 1;
const fileType = parseInt(routerQuery?.fileType + '') || 2;

//监听
watch(() => [
    useAppState.getCollapse
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreData('TreeExpandKeys') || [])
const TreeExpandedKeys = ref(getStoreData('TreeExpandedKeys') || [])
const TreeCurrentNodeKey = ref(getStoreData('TreeCurrentNodeKey') || '')

//渲染完成
onMounted(() => {
    const nodeKey = TreeCurrentNodeKey.value
    if (dataType === 2 && dataId) {
        getYearDateTree()
        queryKey.value = nodeKey
        searchForm.value.queryDate = nodeKey
        searchForm.value.current = 1;
        getTableData()
    } else {
        queryKey.value = ''
    }
})

//获取时间结构
const dateElTreeData = ref([])
const getYearDateTree = async () => {
    const { error, code, data } = await imageApi.getYearDateTree({
        projectId: projectId.value,
        contractId: contractId.value,
        classifyId: dataId
    })
    //处理数据
    if (!error && code === 200) {
        dateElTreeData.value = getArrValue(data)
    } else {
        dateElTreeData.value = []
    }
}
//日期树被点击
const nodeDataInfo = ref({})
const dateWbsElTreeClick = ({data, keys, key}) => {
    queryKey.value = key
    nodeDataInfo.value = data
    //缓存自动展开
    TreeExpandedKeys.value = keys
    TreeCurrentNodeKey.value = key
    setStoreData('TreeExpandedKeys', keys)
    setStoreData('TreeCurrentNodeKey', key)
    //改变搜索表单数据
    searchForm.value.queryDate = data['hierarchy'] || ''
    searchForm.value.wbsIdsStr = null
    searchForm.value.current = 1;
    getTableData()
}

//项目树被点击
const nodeWbsElTreeClick = ({data, keys}) => {
    if (data.leaf === true) {
        nodeDataInfo.value = data
        queryKey.value = data['primaryKeyId'] || ''
        //缓存自动展开
        TreeAutoExpandKeys.value = keys
        setStoreData('TreeExpandKeys', keys)
        //改变搜索表单数据
        searchForm.value.queryDate = null
        searchForm.value.wbsIdsStr = data?.primaryKeyId || ''
        searchForm.value.current = 1;
        getTableData()
    } else {
        queryKey.value = ''
        nodeDataInfo.value = {}
        searchForm.value.queryDate = null
        searchForm.value.wbsIdsStr = null
        tableListData.value = []
        searchForm.value.total = 0
    }
}

//搜索和分页数据
const queryKey = ref(null)
const searchForm = ref({
    queryStr: null, classifyId: dataId, wbsIdsStr: null,
    current: 1, size: 20, total: 0
})

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchClick()
    }
}

//搜索
const searchClick = () => {
    if (queryKey.value) {
        searchForm.value.current = 1;
        getTableData()
    } else {
        window?.$message?.warning('请先在左边选择一个树节点')
    }
}

//分页被点击
const pageChange = ({current, size}) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//获取数据
const tableListRef = ref(null)
const tableLoading = ref(false)
const tableListData = ref([])
const tableListColumn = ref([
    {key:'info', name: '文件详情'},
    {key:'textContent', name: '文字说明'},
    {key:'operate', name: '操作', align: 'center', width: '130'},
])
const getTableData = async () => {
    tableLoading.value = true
    const {error, code, data} = await imageApi.getPageList({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value
    })
    //判断状态
    tableLoading.value = false
    if (!error && code === 200) {
        tableListData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] || 0
    } else {
        tableListData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([]);
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item??'') !== '';
    })
}

//处理图片预览问题
const setImageUrl = (url) => {
    if (url) {
        const urlArr = url.split(',')
        if (urlArr.length > 0 && urlArr[0]) {
            return urlArr[0]
        } else {
            return ''
        }
    } else {
        return ''
    }
}

//预览
const previewVideoUrl = ref('')
const previewVideoModal = ref(false)
const previewClick = async ({id,type,imageUrl}) => {
    if (imageUrl) {
        if (parseInt(type) === 1) {
            previewVideoUrl.value = imageUrl
            previewVideoModal.value = true
        } else {
            const {error, code, data} = await imageApi.imageClassificationFile({ids: id}, false)
            //判断状态
            const imgUrl = getObjNullValue(data)
            if (!error && code === 200 && imgUrl) {
                window.open(data?.data,"_blank");
            } else {
                window.$message?.warning('预览资料文件异常');
            }
        }
    } else {
        window.$message?.warning('暂无可预览的资料文件');
    }
}

//新增文件
const addFormFile = () => {
    router.push({
        path: '/other-file/image-form',
        query: {
            wbsId: queryKey.value,  //树节点ID
            dataType: dataType,     //存储目录格式 1按部位存储，2按日期存储
            fileType: fileType,     //文件类型，1视频文件，2图片文件
            classifyId: dataId,     //classifyId,分类ID,
        }
    })
}

//编辑修改
const editClick = ({id}) => {
    router.push({
        path: '/other-file/image-form',
        query: {
            wbsId: queryKey.value,  //树节点ID
            dataType: dataType,     //存储目录格式 1按部位存储，2按日期存储
            fileType: fileType,     //文件类型，1视频文件，2图片文件
            classifyId: dataId,     //classifyId,分类ID,
            id: id  //数据ID
        }
    })
}

//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}

//下载文件
const downloadLoading = ref(false)
const downloadClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        downloadLoading.value = true
        const ids = rowsToId(rows)
        const { error, disposition, res } = await imageApi.batchDownloadFileToZip({ids: ids}, false)
        //判断状态
        if (!error) {
            if (disposition) {
                downloadBlob(res,disposition)
            } else {
                window.$message?.error('下载异常')
            }
        }
    } else {
        window.$message?.warning('请先勾选需要下载的资料文件');
    }
}

//删除文件
const delLoading = ref(false)
const delClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        const ids = rowsToId(rows)
        window?.$messageBox?.alert('是否删除勾选的资料文件？', '删除提醒', {
            showCancelButton: true,
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    removeImageclassifyFile(ids)
                }
            }
        })
    } else {
        window.$message?.warning('请先勾选需要删除的资料文件');
    }
}
const removeImageclassifyFile = async (ids) => {
    delLoading.value = true
    const {error, code} = await imageApi.removeImageclassifyFile({ids: ids}, false)
    //判断状态
    delLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除异常')
    }
}

//回到影像资料页
const goToBack = () => {
    router.push({path: '/other-file/image-data'})
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(dataType === 1 ? 382 : 220);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        const diffVal = ve.clientX - leftNum;
        const minWidth = dataType === 1 ? 310 : 200
        const maxWidth = dataType === 1 ? 900 : 300
        if(diffVal >= minWidth && diffVal <= maxWidth) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
@import '../../styles/other-file/image-view.scss';
</style>

<style lang="scss">

</style>
