<template>
    <div class="hc-page-layout-box">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'">
            <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>
                 <HcTree :projectId="projectId" :contractId="contractId" @nodeTap="nodeElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard>
               <template #header>
                    <div class="hc-card-header-table-title">
                      已形成的案卷
                  </div>
                </template>
                <template #extra>
                <!--transfer_initial_expert_btn_sampling-->
                    <HcTooltip keys="archives_tuning_btn_num">
                        <el-button hc-btn>
                            <HcIcon name="folder-shared"/>
                            <span>档号整理</span>
                        </el-button>
                    </HcTooltip>
                  <HcTooltip keys="archives_tuning_btn_lock">
                    <el-button hc-btn :disabled="tableCheckedKeys.length <= 0">
                        <HcIcon name="file-lock"/>
                        <span>档案锁定</span>
                    </el-button>
                  </HcTooltip>
                    <HcTooltip keys="archives_tuning_btn_remove">
                        <el-button hc-btn @click="movesClick" :disabled="tableCheckedKeys.length <= 0">
                            <HcIcon name="git-pull-request"/>
                            <span>跨目录移动</span>
                        </el-button>
                    </HcTooltip>
                   <HcTooltip keys="archives_tuning_btn_edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="batchEditClick">
                            <HcIcon name="edit"/>
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="archives_tuning_btn_disassemble">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delModalClick">
                            <HcIcon name="archive-drawer"/>
                            <span>拆卷</span>
                        </el-button>
                    </HcTooltip>
                   <HcTooltip keys="archives_tuning_btn_del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delModalClick">
                            <HcIcon name="delete-bin"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                   
            </template>
                <div class="body" :class="tableFileShow?'file-table':''">
                    <div class="hc-c-table-box">
                        <HcTable ref="tableRef" 
                        :column="tableColumn" 
                        :datas="tableData" 
                        :loading="tableLoading" 
                        isCheck 
                        @selection-change="tableSelection" 
                        @row-click="tableRowClick"
                        :ui="hoverHand?'hover-hand':''"
                        >
                            <template #table-column-header-num>
                                <HcTooltip keys="archives_tuning_btn_sort">
                                    <span class="text-link text-lg" @click="tableSortClick">
                                        <HcIcon name="arrow-up-down"/>
                                    </span>
                                </HcTooltip>
                            </template>
                        </HcTable>
                    </div>
                    <div class="hc-f-table-box" v-if="tableFileShow">
                        <div class="header-box">
                            <div class="header">卷内文件</div>
                            <div>
                                <HcIcon name="edit" @click="batchEditClick"  class="hc-icon-close"  :class="tableCheckedKeys.length >0 ? 'text-hover' : 'text-disable'" style=" color:rgb(64, 149, 229);"/>
                                <HcIcon name="delete-bin" @click="delModalClick" class="hc-icon-close text-hover" :class="tableCheckedKeys.length >0 ? 'text-hover' : 'text-disable'"  style="margin-left:5px;margin-right:5px;color: rgb(189, 49, 36);"/>
                                <HcIcon name="close" @click="closetableFile" class="hc-icon-close text-hover" style=" color:rgb(64, 149, 229);"/>
                            </div>

                        </div>
                        <div class="hc-file-table-box">
                            <HcTable 
                            ref="tableFileRef"
                             :column="innertableColumn" 
                             :datas="tableData" 
                             :loading="tableFileLoading" 
                             isCheck 
                             @selection-change="tableSelection" 
                             @row-click="tableFileRowClick"
                             
                             >
                                 <template #table-column-header-num>
                                    <HcTooltip keys="archives_tuning_btn_sort">
                                        <span class="text-link text-lg" @click="tableSortClick">
                                            <HcIcon name="arrow-up-down"/>
                                        </span>
                                    </HcTooltip>
                                </template>
                            </HcTable>
                        </div>
                    </div>
                </div>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>
  <!--跨目录移动-->
        <HcDialog :show="movesModal" title="跨目录移动" widths="990px" isTable @close="movesModalClose" @save="movesModalSave" :loading="movesModalLoading">
            <div class="hc-moves-transfer-box">
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">
                        <div class="panel-header-label">
                            <el-checkbox class="size-xl space" v-model="movesCheckAll" :indeterminate="isIndeterminate" @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 class="hc-file-checkbox" v-for="item in tableCheckedKeys" :key="item.id">
                                    <el-checkbox class="size-xl space" :label="item.id">{{item.fileName}}</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>
                </div>
                <div class="hc-moves-transfer-panel">
                    <div class="panel-header">选择移动目录</div>
                    <div class="panel-body">
                        <el-scrollbar>
                            <HcTree idPrefix="hc-tree-moves-" :projectId="projectId" :contractId="contractId" isRadio/>
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </HcDialog>
  <!--调整排序-->
        <HcDialog :show="sortModal" title="调整排序" widths="980px" isTable isRowFooter @close="sortModalClose">
            <el-alert title="可拖动排序，也可在后面点击图标，切换排序" type="error" :closable="false"/>
            <div class="hc-table-h">
                <HcTable ui="hc-table-row-drop" :column="sortTableColumn" :datas="sortTableData" :loading="sortTableLoading" isRowDrop @row-drop="sortTableRowDrop">
                    <template #key2="{row}">
                        <span class="text-link">{{row?.key2}}</span>
                    </template>
                    <template #action="{index}">
                    <span class="text-link text-xl" @click="upSortClick(index)">
                        <HcIcon name="arrow-up" fill/>
                    </span>
                        <span class="text-link text-xl ml-2" @click="downSortClick(index)">
                        <HcIcon name="arrow-down" fill/>
                    </span>
                    </template>
                </HcTable>
            </div>
            <template #leftRowFooter>
                <el-button hc-btn @click="sortModalClose">
                    <HcIcon name="close"/>
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="sortModalLoading" @click="sortModalSave">
                    <HcIcon name="check"/>
                    <span>确认</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <HcPages :pages="sortSearchForm" :sizes="[10, 20, 50, 100, 200, 300, 400, 500, 600]" @change="sortPageChange"/>
            </template>
        </HcDialog>

        <!--编辑案卷信息-->
        <el-dialog v-model="showUploadModal" title="编辑文件信息" width="80vw" class="hc-modal-border hc-modal-table">
            <HcTable ui="hc-form-table" :column="tableUploadColumn" :datas="tableUploadData" :loading="uploadSaveLoading">
                <template #fileNumber="{row}">
                    <el-input v-model="row.fileNumber" :class="row['isFileNumber'] ? 'is-error' : ''" @input="tableIsInput($event, row, 'isFileNumber')"/>
                </template>
                <template #fileName="{row}">
                    <el-input v-model="row.fileName" :class="row['isFileName'] ? 'is-error' : ''" @input="tableIsInput($event, row, 'isFileName')"/>
                </template>
                <template #fileTime="{row}">
                    <el-date-picker v-model="row.fileTime" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" :clearable="false"/>
                </template>
                <template #sheetType="{row}" v-if="isBuiltDrawing === 1">
                    <el-select v-model="row.sheetType">
                        <el-option v-for="item in sheetType" :key="item['dictKey']" :label="item['dictValue']" :value="item['dictKey']"/>
                    </el-select>
                </template>
                <template #sheetSource="{row}" v-if="isBuiltDrawing === 1">
                    <el-select v-model="row.sheetSource">
                        <el-option v-for="item in sheetSourceType" :key="item['dictKey']" :label="item['dictValue']" :value="item['dictKey']"/>
                    </el-select>
                </template>
                <template #drawingNo="{row}" v-if="isBuiltDrawing === 1">
                    <el-input v-model="row.drawingNo"/>
                </template>
                <template #citeChangeNumber="{row}" v-if="isBuiltDrawing === 1">
                    <el-input v-model="row.citeChangeNumber"/>
                </template>
                <template #isApproval="{row}">
                    <el-select v-model="row.isApproval">
                        <el-option v-for="item in whetherData" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </template>
                <template #isNeedCertification="{row}">
                    <el-select v-model="row.isNeedCertification">
                        <el-option v-for="item in whetherData" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </template>
                <template #dutyUser="{row}">
                    <el-input v-model="row.dutyUser"/>
                </template>
                <template #action="{row,index}">
                    <el-button type="danger" plain size="small" :loading="row['delBtnLoading']" @click="delUploadData(row,index)">删除</el-button>
                </template>
            </HcTable>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left flex items-center">
                    </div>
                    <div class="right">
                        <el-button size="large" @click="batchUploadCancel">
                            <HcIcon name="close"/>
                            <span>取消</span>
                        </el-button>
                        <el-button type="primary" hc-btn :disabled="uploadsLoading" :loading="uploadSaveLoading" @click="batchUploadSave">
                            <HcIcon name="save"/>
                            <span>保存</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {ref, watch, onMounted} from "vue";
import {useAppStore} from "~src/store";
//import HcTree from "./components/hc-tree.vue"
import HcTree from "~src/components/tree/hc-tree.vue"
import ProjectTree from "./components/ProjectTree.vue"
import {downloadBlob, getArrValue, deepClone} from "vue-utils-plus"
import {delMessage, rowsToId, rowsToIdNumArr} from "~uti/tools";

import projectScanningApi from "~api/other-file/projectScanning";
import {getStoreData, setStoreData} from '~src/utils/storage'

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const isCollapse = ref(useAppState.getCollapse)
const hoverHand = ref(true)

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

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

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

//项目树被点击
const treeNodeInfo = ref({})
const treeDataInfo = ref({})
const nodeIds = ref('')
const isStorageNode = ref(0)
// const isBuiltDrawing = ref(0)
const nodeElTreeClick = ({node, data, keys, key}) => {
    console.log('点击',data);
    setStoreData('scanningTreeExpandKeys', keys)
}
//搜索表单
const searchForm = ref({
    contractId: null, type: null, approval: null, betweenTime: null,
    current: 1, size: 20, total: 0
})

//树相关的变量
const primaryKeyId = ref('')

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({arr,query}) => {
    betweenTime.value = arr
    searchForm.value.betweenTime = query
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1;
    getTableData()
}

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

//表格数据
const tableRef = ref(null)

const tableColumn = ref([])
//设置表头
const setTableColumns = () => {
    if (isBuiltDrawing.value === 1) {
        tableColumn.value = [
            {key:'fileNumber', name: '档号'},
            {key:'fileName', name: '案卷题名',width:500},
            {key:'fileRetion', name: '保管期限'},
            {key:'filePage', name: '总页数'},
        ]


    } else {
        tableColumn.value = [
             {key:'fileNumber', name: '档号', },
            {key:'fileName', name: '案卷题名',width:600},
            {key:'fileRetion', name: '保管期限'},
            {key:'filePage', name: '总页数'},


        ]
    }
}
const tableData = ref([
    {
        id: 1,
        fileNumber: 'xxxx-xxxx-xxx',
        fileName: '30 奉建路PPP项目实施方案的批复-市发展改革委（渝发改交〔2018〕1361号）-20220317090413.pdf',
        filePage: '3',
        isCertificationValue: '未认证',
        isApprovalValue: '待审批',
        fileTime: '2022-12-12',
        fileRetion: '永久',
        dutyUser:'xxxx单位',
         tips:'/'
    },
     {
        id: 1,
        fileNumber: 'xxxx-xxxx-xxx',
        fileName: '30 奉建路PPP项目实施方案的批复-市发展改革委（渝发改交〔2018〕1361号）-20220317090413.pdf',
        filePage: '3',
        isCertificationValue: '未认证',
        isApprovalValue: '待审批',
        fileTime: '2022-12-12',
        fileRetion: '永久',
        dutyUser:'xxxx单位',
        tips:'/'
    },
])
//获取数据
const tableLoading = ref(false)
const getTableData = async () => {

}

const innertableColumn = ref([])
//设置表头
const setInnertableColumn = () => {
    innertableColumn.value = [
            {key:'fileNumber', name: '文件编号'},
            {key:'fileName', name: '文件题名',width:500},

            {key:'fileTime', name: '文件日期'},
            {key:'dutyUser', name: '责任者'},
            {key:'filePage', name: '页数'},
        ]
}
//多选
const tableCheckedKeys = ref([]);
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//删除
const delModalClick = () => {
    delMessage(() => {

    })
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(382);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum;
        if(diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
//跨目录移动
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 movesModalSave = () => {
    movesModal.value = false
}

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

//表格排序
const sortModal = ref(false)
//显示
const tableSortClick = () => {
    sortModal.value = true
}
//表格行被点击
const tableFileShow = ref(false)
const tableRowClick = () => {
    tableFileShow.value = true;
    setInnertableColumn()
}
//收起卷内文件
const closetableFile = () => {
    tableFileShow.value = false
}
//卷内文件点击

const tableFileRowClick = () => {
    showMeteInfo.value = true;

}
//搜索表单
const sortSearchForm = ref({
    current: 1, size: 20, total: 0
})

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

//表格数据
const sortTableColumn = ref([
    {key:'key1', name: '档号', width: 160},
    {key:'key2', name: '案卷名称'},
    {key:'action', name: '排序', width: 90},
])
const sortTableData = ref([
    {
        id: 1,
        key1: 'xxxx-xxxx-xxx',
        key2: '30 奉建路PPP项目实施方案的批复-市发展改革委（渝发改交〔2018〕1361号）-20220317090413.pdf',
    },
    {
        id: 2,
        key1: 'xxxx-xxxx-222',
        key2: '40 奉建路PPP项目实施方案的批复-市发展改革委（渝发改交〔2018〕1361号）-20220317090413.pdf',
    }
])

const sortTableLoading = ref(false)
const getSortTableData = () => {

}

//拖动完成
const sortTableRowDrop = (rows) => {
    sortTableData.value = rows
}

//向下
const downSortClick = (index) => {
    const indexs = index + 1
    const data = sortTableData.value
    if(indexs !== data.length) {
        const tmp = data.splice(indexs,1);
        sortTableData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}

//向上
const upSortClick = (index) => {
    const data = sortTableData.value || []
    if(index !== 0) {
        const tmp = data.splice(index - 1,1);
        sortTableData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}

//保存
const sortModalLoading = ref(false)
const sortModalSave = () => {
    sortModal.value = false
}

//关闭
const sortModalClose = () => {
    sortModal.value = false
}
//编辑
const tableUploadType = ref('add')
const showUploadModal = ref(false)
const isBuiltDrawing = ref(0)
//批量上传保存
const uploadSaveLoading = ref(false)
//批量编辑

//批量编辑
const batchEditClick = () => {
    const rows = deepClone(tableCheckedKeys.value)
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status !== 1 && status !== 2
    })
    //判断状态
    if (result) {
        tableUploadType.value = 'edit'
        setTableUploadColumn()
        uploadSaveLoading.value = false
        tableUploadData.value = rows
        showUploadModal.value = true
    } else {
        window.$message?.warning('已上报或已审批的文件不能编辑')
    }
}



//设置文件表头
const tableUploadColumn = ref([
    {key:'fileNumber', name: '文件编号'},
    {key:'fileName', name: '文件题名'},
    {key:'fileTime', name: '文件日期'},
    {key:'dutyUser', name: '立卷单位'},
    {key:'tips', name: '备注'},

])
const setTableUploadColumn = () => {
    if (isBuiltDrawing.value === 1) {
        tableUploadColumn.value = [
        {key:'fileNumber', name: '文件编号'},
        {key:'fileName', name: '文件题名'},
        {key:'fileTime', name: '文件日期'},
        {key:'dutyUser', name: '立卷单位'},
        {key:'tips', name: '备注'},
        ]
    } else {
        tableUploadColumn.value = [
             {key:'fileNumber', name: '文件编号'},
            {key:'fileName', name: '文件题名'},
            {key:'fileTime', name: '文件日期'},
            {key:'dutyUser', name: '立卷单位'},
            {key:'tips', name: '备注'},
        ]
    }
}
const tableUploadData = ref([])



</script>

<style lang="scss" scoped>
.hc-card-header-table-title{
 font-size: 1.125rem;
line-height: 1.75rem;
}
.rowbox{
    text-align: center;
}

 .body {
        position: relative;
        // height: calc(100% - 140px);
        height: calc(100% - 0px);
        padding: 16px;
        .hc-c-table-box {
            position: relative;
            height: 100%;
        }
        .hc-f-table-box {
            position: relative;
            height: 300px;
            margin-top: 24px;
            background: #f1f5f8;
            .header-box {
                border-bottom: initial;
                display: flex;
                justify-content: space-between;
                height: 60px;
                background-color:var(--el-fill-color-lighter);
                line-height: 60px;
                padding-left: 15px;
                padding-right: 15px;
                .hc-icon-close {
                    font-size: 18px;
                }
            }
            .hc-file-table-box {
                position: relative;
                height: calc(100% - 55px);
            }
        }
        &.file-table .hc-c-table-box {
            height: calc(100% - 324px);
        }
    }
@import '~style/file/scoped/collection.scss';
</style>

<style lang="scss">
@import '~style/file/collection.scss';
.text-disable{
    cursor:not-allowed
}
 .hover-hand{
      cursor: pointer;
  }
</style>
