<template>
    <div class="hc-layout-box">
        <div :style="'width:' + leftWidth + 'px;'" class="hc-layout-left-box">
            <template v-if="dataType === 1">
                <div class="hc-project-box">
                    <div class="hc-project-icon-box">
                        <HcIcon name="stack"/>
                    </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" :contractId="contractId" :projectId="projectId"
                                 @nodeTap="nodeWbsElTreeClick"/>
                    </el-scrollbar>
                </div>
            </template>
            <div v-else class="hc-tree-box date-tree">
                <el-scrollbar>
                    <HcTreeData :autoExpandKeys="TreeExpandedKeys" :datas="dateElTreeData"
                                @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 :disabled="!queryKey && dataType === 1" hc-btn type="primary" @click="addFormFile">
                            <HcIcon name="add_box"/>
                            <span>新增文件</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="image-data-download">
                        <el-button :disabled="tableCheckedKeys.length <= 0" :loading="downloadLoading" hc-btn
                                   @click="downloadClick">
                            <HcIcon name="download"/>
                            <span>下载</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="image-data-del">
                        <el-button :disabled="tableCheckedKeys.length <= 0" :loading="delLoading" hc-btn
                                   @click="delClick">
                            <HcIcon name="delete"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <div class="w-60">
                        <el-input v-model="searchForm.queryStr" clearable placeholder="根据题名名称或拍摄者搜索"
                                  size="large" @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button size="large" type="primary" @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 v-if="row.type !== 1" class="img-box">
                                <HcImg :src="setImageUrl(row.imageUrl)" class="hc-image"/>
                            </div>
                            <div v-else class="img-box">
                                <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 :loading="previewLoading" size="small" text type="primary"
                                       @click="previewClick(row)">查看
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="image-data-edit">
                            <el-button size="small" text type="primary" @click="editClick(row)">编辑</el-button>
                        </HcTooltip>
                    </template>
                </HcTable>
                <template #action>
                    <div class="lr-dialog-footer">
                        <div class="left">
                            <el-button size="large" @click="goToBack">
                                <HcIcon name="arrow-go-back"/>
                                <span>返回</span>
                            </el-button>
                        </div>
                        <div class="right">
                            <HcPages :pages="searchForm" @change="pageChange"/>
                        </div>
                    </div>
                </template>
            </HcCard>
        </div>
        <!--视频预览 弹框-->
        <el-dialog v-model="previewVideoModal" class="hc-modal-border" destroy-on-close title="预览" width="47rem">
            <video v-if="previewVideoUrl" :src="previewVideoUrl" autoplay="autoplay" class="preview-video"
                   controls="controls">
                您的浏览器不支持 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, isString} 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 = ref(routerQuery?.id || '')
const dataType = ref(parseInt(routerQuery?.type + '') || 1);
const fileType = ref(parseInt(routerQuery?.fileType + '') || 2);

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

//监听路由参数改变
watch(() => [
    useRoutes?.query
], ([query]) => {
    dataId.value = query?.id || ''
    dataType.value = parseInt(query?.type + '') || 1
    fileType.value = parseInt(query?.fileType + '') || 2
    initMounted()
}, {deep: true})

watch(contractId, (val) => {
    if (val) {
        console.log(val)
        router.push({
            path: '/other-file/image-data',
        })
    }
})

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

//渲染完成
onMounted(() => {
    initMounted()
})

const initMounted = () => {
    console.log('onMounted')
    const nodeKey = TreeCurrentNodeKey.value
    if (dataType.value === 1) {
        TreeAutoExpandKeys.value = getStoreData('TreeExpandKeys') || []
    } else {
        TreeExpandedKeys.value = getStoreData('TreeExpandedKeys') || []
    }
    if (dataType.value === 2 && dataId.value) {
        getYearDateTree()
        queryKey.value = nodeKey
        //console.log(queryKey.value, '  queryKey.value');
        if (isNaN(queryKey.value) && !isNaN(Date.parse(queryKey.value))) {
            queryKey.value = ''
        }
        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.value
    })
    //处理数据
    if (!error && code === 200) {
        dateElTreeData.value = getArrValue(data)
    } else {
        dateElTreeData.value = []
    }
}
//日期树被点击
const nodeDataInfo = ref({})
const dateWbsElTreeClick = ({data, keys, key}) => {
    // queryKey.value = key
    queryKey.value = ''
    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}) => {
    searchForm.value.wbsIdsStr = data?.primaryKeyId || ''
    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 {
        getTableData()
        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.value, 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: '140'},
])
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 previewLoading = ref(false)
const previewClick = async (item) => {
    const {id, type, imageUrl, margePdfUrl} = item
    if (parseInt(type) === 1) {
        if (imageUrl) {
            previewVideoUrl.value = imageUrl
            previewVideoModal.value = true
        } else {
            window.$message?.warning('暂无可预览的资料文件');
        }
    } else if (parseInt(type) === 2) {
        if (margePdfUrl) {
            window.open(margePdfUrl, "_blank");
        } else {
            previewLoading.value = true
            const {error, code, data} = await imageApi.imageClassificationFile({
                ids: id
            }, false)
            //判断状态
            previewLoading.value = false
            if (!error && code === 200 && isString(data)) {
                item.margePdfUrl = data
                window.open(data, "_blank");
            } else {
                window.$message?.warning('预览资料文件异常');
            }
        }
    }
}

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

//编辑修改
const editClick = ({id}) => {
    router.push({
        path: '/other-file/image-form',
        query: {
            wbsId: queryKey.value,  //树节点ID
            dataType: dataType.value,     //存储目录格式 1按部位存储，2按日期存储
            fileType: fileType.value,     //文件类型，1视频文件，2图片文件
            classifyId: dataId.value,     //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.value === 1 ? 382 : 220);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        const diffVal = ve.clientX - leftNum;
        const minWidth = dataType.value === 1 ? 310 : 200
        const maxWidth = dataType.value === 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">
.preview-video {
    width: 100%;
}
</style>
