<template>
    <div class="hc-page-box">
        <hc-page-split>
            <template #left>
                <hc-card scrollbar>
                    <!-- Element Plus 菜单组件 -->
                    <ElMenu
                        v-if="folderData.length > 0"
                        v-loading="folderLoading"
                        default-active="1-1"
                        class="custom-menu"
                        unique-opened
                      
                        @select="handleSelect"
                    >
                        <!-- 渲染动态菜单 -->
                        <template v-for="item in folderData" :key="item.id">
                            <MenuItem :menu-item-data="item" :selected-key-path="selectedKeyPath" />
                        </template>
                    </ElMenu>
                    <div v-else class="mt-40">
                        <hc-empty />
                    </div>
                </hc-card>
            </template>
            <hc-new-card>
                <template #extra>
                    <el-button hc-btn type="danger" :loading="scanLoading" @click="scanClick">开始扫描</el-button>
                </template>
                <template #header>
                    <el-button hc-btn color="#12B9A7" class="text-white" @click="movesClick">移动</el-button>
                    <el-button hc-btn color="#149BF4" class="text-white">自动识别</el-button>
                    <el-button hc-btn class="text-white" color="#149BF4" :disabled="!tableCheckedKeys.length" @click="editClick">编辑</el-button>
                    <el-button v-del-com:[delClick] hc-btn type="danger" :disabled="!tableCheckedKeys.length">删除</el-button>
                </template>

                <HcTable
                    ref="tableRef" :check-style="{ width: 29 }" :column="tableColumn" :datas="tableData"
                    :index-style="{ width: 60 }" :loading="tableLoading" is-check is-new
                    :cell-style="tableCellStyle"
                    @selection-change="tableSelection"
                >
                    <template #fileName="{ row }">
                        <span class="text-link" @click="viewPdf(row.ossUrl)">{{ row?.fileName }}</span>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" :sizes="[20, 50, 100, 200, 300, 500]" @change="pageChange" />
                </template>
            </hc-new-card>
        </hc-page-split>
        <!-- 移动 -->
        <hc-new-dialog v-model="movesModal" :loading="movesModalLoading" is-table title="跨目录移动" widths="80vw" @close="movesModalClose" @save="movesModalSave">
            <div class="hc-moves-transfer-box">
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">
                        <div class="panel-header-label">
                            <el-checkbox v-model="movesCheckAll" :indeterminate="isIndeterminate" class="space size-xl" @change="handleCheckAllChange">
                                选择需要迁移的文件
                            </el-checkbox>
                        </div>
                        <div class="panel-header-extra">{{ checkedMoves.length }}/{{ tableCheckedKeys.length }}</div>
                    </div>
                    <div class="panel-body">
                        <el-scrollbar>
                            <el-checkbox-group v-model="checkedMoves" @change="handleCheckedMovesChange">
                                <div v-for="item in tableCheckedKeys" :key="item.id" class="hc-file-checkbox">
                                    <el-checkbox :value="item.id" class="space size-xl">{{ item.name }}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="hc-moves-transfer-buttons">
                    <!-- <el-button hc-btn _icon size="small"
                               :type="tableCheckedKeys.length <= 0 || checkedMoves.length <= 0 ? '' : 'primary'"
                               :disabled="tableCheckedKeys.length <= 0 || checkedMoves.length <= 0">
                        <HcIcon name="arrow-right"/>
                    </el-button> -->
                    <HcIcon name="arrow-right-double" style="font-size: 22px;" type="primary" />
                </div>
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">选择移动目录</div>
                    <div class="panel-body">
                        <el-scrollbar>
                            <HcTree :contract-id="contractId" :is-show-menu="false" :project-id="projectId" id-prefix="hc-tree-moves-" is-radio @noderadio="nodeRadio" />
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </hc-new-dialog>
        <!-- 编辑 -->
        <hc-new-dialog v-model="editModal" :loading="editLoading" is-table title="编辑" widths="60vw" @close="editModalClose" @save="editModalSave">
            <HcTable
                ui="hc-form-table" is-new :is-index="false" 
                :column="tableEditColumn" :datas="tableEditData" 
            >
                <template #fileNum="{ row }">
                    <el-input v-model="row.fileNum" />
                </template>
                <template #fileName="{ row }">
                    <el-input v-model="row.fileName" type="textarea" />
                </template>
      
             
                <template #responsible="{ row }">
                    <el-input v-model="row.responsible" type="textarea" />
                </template>
                <template #fileDate="{ row }">
                    <el-date-picker v-model="row.fileDate" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" />
                </template>
            </HcTable>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import scanApi from '~api/archiveFile/scanning'
import { useAppStore } from '~src/store'
import HcTree from '~src/components/tree/hc-tree.vue'
import { deepClone, getArrValue } from 'js-fast-way'
import MenuItem from './MenuItem.vue' // 导入递归组件
import { toPdfPage } from '~uti/btn-auth'
const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)
const projectId = ref(useAppState.getProjectId)
const folderLoading = ref(false)
onMounted(()=>{
    getMenuFolderData()
  
})
//菜单数据
const folderData = ref([])
const isCollapse = ref(false)
// 记录当前选中的完整路径
const selectedKeyPath = ref([])



const folderId = ref('') // 当前选中的文件夹ID
// 处理菜单选择事件 - 记录完整路径
const handleSelect = (key, keyPath) => {
    selectedKeyPath.value = keyPath
  folderId.value = key
    getTableData()

}
const getMenuFolderData = async ()=>{
        folderLoading.value = true
    const { error, code, data } = await scanApi.getScanFolder({
        ...searchForm.value,
        projectId:  111,
        contractId: 123,
   
    })
    folderLoading.value = false
    if (!error && code === 200) {
        folderData.value = getArrValue(data)
     
    } else {
        folderData.value = []

    }
}
//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
}
//搜索表单
const searchForm = ref({
    contractId: null, type: null, approval: null, betweenTime: null,
    current: 1, size: 20, total: 0,
})
//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'digitalNum', name: '数字编号' },
    { key: 'fileNum', name: '文件编号' },
    { key: 'fileName', name: '文件题名' },
    { key: 'fileSize', name: '文件页数' },
    { key: 'fileDate', name: '文件日期' },
    { key: 'responsible', name: '责任者' },

])
const tableData = ref([ ])
const viewPdf = (ossUrl)=>{
    toPdfPage(ossUrl)
}
//设置单元格的样式
const tableCellStyle = ({ row, column, rowIndex, columnIndex }) => {
    if (row.id === 1 && column.property === 'name') {
        return {
            backgroundColor: '#FF7D43',
            color: 'black',
        }
    }
}
//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await scanApi.getScanFile({
        ...searchForm.value,
         projectId:  111,
        contractId: 123,
        folderId: folderId.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}
//移动

//跨目录移动
const movesModal = ref(false)
const movesClick = () => {
    movesModal.value = true
}

//选择需要迁移的文件
const movesCheckAll = ref(false)
const isIndeterminate = ref(true)
const checkedMoves = ref([])

//全选
const handleCheckAllChange = (val) => {
    const checked = tableCheckedKeys.value
    const keys = rowsToIdNumArr(checked)
    checkedMoves.value = val ? keys : []
    isIndeterminate.value = false
}

//勾选
const handleCheckedMovesChange = (value) => {

    const keys = tableCheckedKeys.value
    const checkedCount = value.length
    movesCheckAll.value = checkedCount === keys.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < keys.length
}

//保存
const movesModalLoading = ref(false)
const chnodeId = ref('')
const movesModalSave = async () => {
    movesModalLoading.value = true
    console.log(checkedMoves.value, 'checkedMoves.value')
    let ids = checkedMoves.value.join(',')

    const { error, code, data, msg } = await tuningApi.moveArchive({
        ids: ids,
        nodeId: chnodeId.value,
    })
    movesModalLoading.value = false
    if (!error && code === 200) {
        console.log(msg, 'msg')
        window.$message?.success(msg)
        getTableData()
    } else {
        window.$message?.warning(msg)
    }
    movesModal.value = false
}

//关闭
const movesModalClose = () => {
    movesModal.value = false
}

//开始扫描
const scanLoading = ref(false)
const scanClick = async () => {
    scanLoading.value = true
     const { error, code, data, msg } = await scanApi.startOrEndScan({
        type: 1,
        contractId: contractId.value,
    })
    scanLoading.value = false
    if (!error && code === 200) {
        window.$message?.success(msg)
        getTableData()
    } else {
        window.$message?.warning(msg)
    }
    movesModal.value = false
}
//编辑
const editModal = ref(false)
const editClick = () => {
    editModal.value = true
    tableEditData.value = deepClone(tableCheckedKeys.value)
}
const editLoading = ref(false)
const editModalSave = async () => {
        editLoading.value = true
    const { error, code } = await scanApi.updateScanFile(
         tableEditData.value)
    //判断状态
    editLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        editModalClose()
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }
}
const editModalClose = () => {
    editModal.value = false
      tableRef.value?.clearSelection()
}
const tableEditColumn = ref([

    { key: 'fileNum', name: '文件编号' },
    { key: 'fileName', name: '文件题名' },
    { key: 'fileDate', name: '文件日期' },
    { key: 'responsible', name: '责任者' },
])
const tableEditData = ref([])

const delClick = async (_, resolve) => {
    let ids = []
    tableCheckedKeys.value.forEach((element)=>{
        ids.push(element.id)
    })
    const { error, code } = await scanApi.deleteScanFile({
        ids: ids.join(','),
    })
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('操作成功')
        getTableData()
    }
    resolve()
}
</script>

<style scoped lang="scss">
.custom-menu {
    width: 100%;
    min-height: 400px;
    border-right: none !important;
}
.hc-card {
    position: relative;
}
.hc-moves-transfer-box {
    position: relative;
    display: flex;
    height: 100%;
    align-items: center;
    .hc-moves-transfer-panel {
        width: 47%;
        position: relative;
        height: 100%;
        background: #ffffff;
        display: inline-block;
        text-align: left;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        .panel-header {
            position: relative;
            background: #f5f7fa;
            display: flex;
            align-items: center;
            height: 48px;
            padding: 0 16px;
            border-bottom: 1px solid #ebeef5;
            border-radius: 4px 4px 0 0;
            .panel-header-label {
                position: relative;
                flex: 1;
            }
            .panel-header-extra {
                color: #aaaaaa;
            }
        }
        .panel-body {
            position: relative;
            padding: 16px;
            height: calc(100% - 48px);
            
            .hc-file-checkbox {
                position: relative;
            }
            .hc-file-checkbox + .hc-file-checkbox {
                margin-top: 16px;
            }
        }
    }
    .hc-moves-transfer-buttons {
        display: inline-block;
        vertical-align: middle;
        padding: 0 16px;
    }
}
</style>
    