<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" :disabled="!folderId" @click="movesClick">移动</el-button>
                    <!-- <el-button hc-btn color="#149BF4" class="text-white">自动识别</el-button> -->
                    <HcTooltip keys="file_records_btn_split">
                        <el-badge :value="taskMount" class="ml-1 mr-4 cursor-pointer" :offset="[5, 5]" @click.native.stop="taskCountClick">
                            <el-button hc-btn style="background-color: #8B5CF6; border-color: #8B5CF6; color:white" @click.native.stop="splitClick">自动识别</el-button>
                            <template #content="{ value }">
                                <div class="custom-content">
                                    <span>{{ value }}</span>
                                </div>
                            </template>
                        </el-badge>
                    </HcTooltip>
                    <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 }}/{{ fileDatasList.length }}</div>
                    </div>
                    <div class="panel-body">
                        <el-scrollbar v-loading="fileDatasListLoading">
                            <el-checkbox-group v-model="checkedMoves" @change="handleCheckedMovesChange">
                                <!-- 为文件名容器添加自定义class以便设置样式 -->
                                <div v-for="item in fileDatasList" :key="item.id" class="file-item">
                                    <el-checkbox :label="item">
                                        <span class="file-name">{{ item.fileName }}</span>
                                    </el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="hc-moves-transfer-buttons">
                    <HcIcon name="arrow-right-double" style="font-size: 22px;" type="primary" />
                </div>
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">选择移动目录</div>
                    <div v-loading="treePanelLoading" class="panel-body">
                        <el-scrollbar>
                            <HcTree
                                :contract-id="contractId" :is-show-menu="false" :project-id="projectId"
                                :show-radio-fun="showRadioFun" id-prefix="hc-tree-moves-" is-radio
                                @radio-change="radioChange" @node-loading="panelTreeLoading"
                            />
                        </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>
        <!-- 自动识别列表信息 -->
        <!-- 分解列表信息 -->
        <hc-new-dialog v-model="splitListModal" title="自动识别列表信息" widths="50vw" :footer="false" height="500px" @close="splitListModalClose">
            <HcTable
                heights="calc(100% - 50px)"

                :column="splitListColumn"
                :datas="splitList"
                :loading="splitListLoading"
                is-new
                :index-style="{ width: 70 }"
            >
                <template #fileNumber="{ row }">
                    <span>{{ row.fileNumber }}</span>
                </template>
                <template #name="{ row }">
                    <span>{{ row.name }}</span>
                </template>
                <template #status="{ row }">
                    <span>{{ row.status }}</span>
                </template>
                <template #createTime="{ row }">
                    <span>{{ row.createTime }}</span>
                </template>
            </HcTable>
        </hc-new-dialog>
        
        <!-- 分解文件 -->
        <hc-new-dialog v-model="splitModal" title="自动识别" widths="40vw" :loading="splitSaveLoad" @close="splitModalClose" @save="splitSave">
            <div class="split-modal-content">
                <div class="mb-6 text-4 font-bold">
                    本次识别共
                    <span class="text-red">【{{ splitInfo?.fileCount }}】</span>
                    卷，预计耗费时长
                    <span class="text-red">【{{ splitInfo?.taskTime }}】</span>
                    分钟，分解完成之后，序号图标会变成      <HcIcon name="checkbox-circle" style="color:lightgreen" />
                </div>
                <div class="mb-6 text-orange">请不要重复提交，过会儿再来查看，识别好的文件在对应节点可查看</div>
                <!-- <el-button type="primary" size="large" class="split-confirm-btn" hc-btn @click="splitModalClose">好的，我知道了</el-button> -->
            </div>
        </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 { arrToId, deepClone, getArrValue, getObjValue } from 'js-fast-way'
import MenuItem from './MenuItem.vue' // 导入递归组件
import { toPdfPage } from '~uti/btn-auth'

import tasksApi from '~api/tasks/data'
import { HcFirmMsg, HcUploadFileApi } from 'hc-vue3-ui'
const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)
const projectId = ref(useAppState.getProjectId)
const folderLoading = ref(false)
onMounted(()=>{
    getMenuFolderData()
         getSplitInfo()
  
})
//菜单数据
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: projectId.value,
        contractId: contractId.value,
   
    })
    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: projectId.value,
        contractId: contractId.value,
        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 treePanelLoading = ref(false)
const panelTreeLoading = () => {
    treePanelLoading.value = false
}

const movesModal = ref(false)
const movesClick = async () => {
    movesModal.value = true
    checkedMoves.value = []
    movesCheckAll.value = false
    treePanelLoading.value = true
    fileDatasListLoading.value = true
    const { error, code, data } = await scanApi.getScanFile({
        ...searchForm.value,
        size: 5000,
        projectId: projectId.value,
        contractId: contractId.value,
        folderId: folderId.value,
        move: 0,
    })
    fileDatasListLoading.value = false
    if (!error && code === 200) {
        fileDatasList.value = getArrValue(data['records'])
    } else {
        fileDatasList.value = []
    }
}

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

//左侧待迁移文件
const fileDatasList = ref([])
const fileDatasListLoading = ref(false)
//全选
const handleCheckAllChange = (val) => {
    console.log(val, 'val')
    const checked = fileDatasList.value
    checkedMoves.value = val ? checked : []
    isIndeterminate.value = false
}

//勾选
const handleCheckedMovesChange = (value) => {
    const keys = fileDatasList.value
    const checkedCount = value.length
    movesCheckAll.value = checkedCount === keys.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < keys.length
}

//右侧radio
let radioNodeId = ''
const radioChange = (id) => {
    //console.log(id)
    radioNodeId = id
}

//只显示储存节点的单选
const showRadioFun = (data) => {
    if (data.isStorageNode == 1) {
        return true
    } else {
        return false
    }
}

//保存
const movesModalLoading = ref(false)
const movesModalSave = async () => {
    const keys = arrToId(checkedMoves.value).split(',')
    let ids = keys
    console.log(keys, 'keys')
    
    if (checkedMoves.value.length < 1) {
        window.$message?.warning('请勾选需要迁移的文件')
        return
    }
    if (radioNodeId == '') {
        window.$message?.warning('请选择要移动到的节点')
        return
    }
    movesModalLoading.value = true
    const { error, code, data } = await scanApi.moveScanFile({
        ids: ids,
        nodeId: radioNodeId,
    })
    movesModalLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        movesModal.value = false
        getTableData()
    } else {
        window.$message?.error('保存失败')
    }

}

//关闭
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()
}
//自动识别功能

const taskMount = ref('')
const splitLoad = ref(false)
const splitClick = async ()=>{
    console.log('分解文件')
    splitLoad.value = true
    const rows = tableCheckedKeys.value
    if (rows.length < 1) {
        // await window.$message.warning('没有选择案卷时，将会对该合同段下所有案卷进行分解')
         HcFirmMsg({
        title: '操作确认',
        text: '没有选择案卷时，将会对该合同段下所有案卷进行识别',
    }, async (resolve) => {
                     getSaveInfoData()
                 resolve() //关闭弹窗的回调
            })
    } else {
        getSaveInfoData()


    }

    // splitModal.value = true
}
const getSaveInfoData = async ()=>{
    const rows = tableCheckedKeys.value
    const { error, code, data, msg } = await tasksApi.getSaveInfo({
                            contractId:contractId.value,
                            projectId:projectId.value,
                            ids:rows.map(item=>item.id).join(','),
                            dataType:2,
                        })
                        splitLoad.value = false
                        //处理数据
                    
                        
                        if (!error && code === 200) {
                            splitInfo.value = data
                            splitModal.value = true
                            splitInfo.value = getObjValue(data) || {}

                        } else {
                            window.$message.error(msg)
                        }
                        //  splitModal.value = true
}
const splitSaveLoad = ref(false)
const splitSave = async ()=>{
     const rows = tableCheckedKeys.value
     splitSaveLoad.value = true

              const { error, code, data, msg } = await tasksApi.saveSplit({
                            contractId:contractId.value,
                            projectId:projectId.value,
                            ids:rows.map(item=>item.id).join(','),
                            dataType:2,
                        })
                        splitSaveLoad.value = false
                        //处理数据
                    
                        
                        if (!error && code === 200) {
                            splitInfo.value = data
                            splitModal.value = true
                            splitInfo.value = getObjValue(data) || {}
                            window.$message.success(msg)
                             getSplitInfo()
                            splitModal.value = false
                            getTableData()


                        } else {
                            window.$message.error(msg)
                        }
}


const splitInfo = ref({})
const splitList = ref([
    
])
// 在script setup中添加
const splitListModal = ref(false)
const splitListLoading = ref(false)
const splitListColumn = ref([
    { key: 'taskName', name: '任务名称' },
    { key: 'finished', name: '完成数量', width: 100 },
    { key: 'toolCount', name: '总条数', width: 100 },
  
])

const splitListModalClose = () => {
    splitListModal.value = false
}

// 修改taskCountClick方法
const taskCountClick = async () => {
    await getSplitInfo()
    splitListModal.value = true
}//查询任务信息
const getSplitInfo = async ()=>{
    const { error, code, data } = await tasksApi.selectTaskSplit({
        contractId:contractId.value,
        projectId:projectId.value,
        dataType:2,

    })
    //处理数据
    if (!error && code === 200) {
        splitList.value = data['records']
     
        if (data['records'].length > 0) {
            taskMount.value = data['total']
        }
    } else {
        splitList.value = []
        taskMount.value = ''
    }
}
const splitModal = ref(false)
const splitModalClose = ()=>{
    splitModal.value = false
}
</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: 15px;
            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>

<style scoped>
/* 解决文件名过长问题的样式 */
.file-item {
  margin-bottom: 10px; /* 增加项目之间的间距 */
  margin-top: 8px;
}

.file-name {
  white-space: normal; /* 允许换行 */
  word-wrap: break-word; /* 长单词换行 */
  word-break: break-all; /* 强制换行 */
  display: inline-block;

  vertical-align: middle;
  line-height: 1.5; /* 调整行高，使多行文本更易读 */
}
</style>