<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"  v-loading="treeLoading" element-loading-text="加载中...">
                <el-scrollbar>
                    <HcTree :projectId="projectId" :contractId="contractId" @nodeTap="nodeElTreeClick"  @nodeLoading="treeNodeLoading" :autoExpandKeys="treeAutoExpandKeys" @menuTap="ElTreeMenuClick"/>
                    <!--ProjectTree :datas="ElTreeData" :autoExpandKeys="TreeAutoExpandKeys" @nodeTap="nodeElTreeClick" :ischeck="false"/-->
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard title="已形成的案卷">
                <!-- <template  #header>
                   <div class="hc-card-header-table-title">
                      已形成的案卷
                  </div>
                </template> -->
                <template  #extra>
                    <div class="demo-progress">
                        <el-progress
                        :text-inside="true"
                        :stroke-width="30"
                        :percentage="propercent"
                        status="success"
                        />
                    </div>
                
                    <HcTooltip keys="archives_rolling_btn_update">
                        <el-button type="primary" hc-btn @click="updateArchive" :loading="updateArchiveLoad">
                            <HcIcon name="git-pull-request"/>
                            <span>立即更新立卷</span>
                        </el-button>
                    </HcTooltip>
                </template>

                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection">
                    <template #name="{row}">
                                        <span class="text-link" @click="viewPdf(row.id)">{{row?.name}}</span>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

    </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 projectScanningApi from "~api/other-file/projectScanning";
import archiveFileApi from "~api/archiveFile/archiveFileAuto.js";
import {getStoreValue, setStoreValue} from '~src/utils/storage'
import {downloadBlob, getArrValue, deepClone} from "js-fast-way"
//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const isCollapse = ref(useAppState.getCollapse)
import tuningApi from "~api/archiveConfig/tuning.js";

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

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

//树加载
const treeLoading = ref(true)
const treeNodeLoading = () => {
    treeLoading.value = false
}

//搜索表单
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([
     {key:'fileNumber', name: '档号'},
    {key:'name', name: '案卷题名', width: 600},
    {key:'storageTimeValue', name: '保管期限'},
    {key:'pageN', name: '总页数'},

])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await tuningApi.pageByArchive({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
        isArchive :1
    })
    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 delModalClick = () => {

}

//左右拖动，改变树形结构宽度
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 ElTreeData = ref([])
let childtreedata = ref([])//子目录信息
const getClassIfyList = async () => {
    const { error, code, data } = await projectScanningApi.getClassIfyList({
        projectId: projectId.value,
        contractId: contractId.value
    })
    //处理数据
    if (!error && code === 200) {
        ElTreeData.value = getArrValue(data)
    } else {
        ElTreeData.value = []
    }
    console.log(ElTreeData.value,'ElTreeData');
}
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('scanningTreeExpandKeys') || [])

//项目树被点击
const treeAutoExpandKeys = ref(getStoreValue('rollingExpandKeys') || [])
const nodeElTreeClick = ({node, data, keys, key}) => {
    console.log('点击',data);
    searchForm.value.total = 0
    searchForm.value.current = 1
    searchForm.value.size = 20
    searchForm.value.nodeIds = data.id || '';
    getTableData()
    //缓存展开的节点
    setStoreValue('rollingExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []
}
//树菜单被点击
const ElTreeMenuClick = async ({key, node, data, keys}) => {
    setStoreValue('rollingExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []
 
}
//预览pdf
const viewPdf=async(id)=>{
    window.$message?.info('预览案卷需要合并pdf，需要一点时间')
    const { error, code, data,msg } = await tuningApi.printArchive({
       id:id
    })
    if (!error && code === 200) {
      if(data){
        window.open(data, '_blank')
      }else{
        window.$message?.warning('文件不存在')
      }
       
    } else {
        window.$message?.warning(msg)
    }
}
//更新立卷
const updateArchiveLoad=ref(false)
const propercent=ref(0)
const updateArchive=async()=>{
    updateArchiveLoad.value=true
    const { error, code, data,msg } = await tuningApi.archiveAutoMethod({
        projectId:projectId.value,
        contractId:contractId.value
    })
    updateArchiveLoad.value=false
    if (!error && code === 200) {
        window.$message?.success(data)
       
        if( propercent.value!==100){
            Verification()
        }else if(propercent.value===100){
            propercent.value=0
            count.value=0
            Verification()
        }
    } 
    else {
        window.$message?.warning(msg)
    }
}
const timer=ref(null)
let count = ref(0); // 倒计时
//更新立卷进度
const updateArchiveprogress=async()=>{

    const { error, code, data,msg } = await tuningApi.archiveAutoPercentComplete({
        projectId:projectId.value,
        contractId:contractId.value
    })

    if (!error && code === 200) {
        console.log(data);
        if(data==100){
            console.log(11111);
            count.value=100
        }
        propercent.value=data
    } 
}

//循环请求接口
const Verification = () => {
        timer.value = setInterval(() => {
            if(count.value==100){
                console.log('停着');
                clearInterval(timer.value);
            }else{
                updateArchiveprogress();// 请求数据 
            }
        
       
    }, 30000);
    
//    if(count.value===100){
//     console.log(111111222);
//     clearInterval(timer.value);
//    }
};

   
    
    

</script>

<style lang="scss" scoped>
.hc-card-header-table-title{
 font-size: 1.125rem;
line-height: 1.75rem;
}
.demo-progress .el-progress--line {
  margin-bottom: 15px;
  width: 350px;
  margin-top: 15px;
  margin-right: 15px;
}

</style>
