<template>
    <hc-body split>
        <template #left>
            <hc-new-card class="is-tree-card" scrollbar>
                <hc-lazy-tree v-if="projectId" tree-key="id" :h-props="treeProps" @load="treeLoadNode" @node-tap="treeNodeTap" />
            </hc-new-card>
        </template>
        <hc-new-card>
            <template #header>
                <div class="input-search flex-1">
                    <el-input v-model="searchForm.title" clearable block placeholder="可按案卷题名关键字模糊搜索；展开更多搜索可使用更多搜索条件" @keyup="queryEvent">
                        <template #prefix>
                            <i class="i-iconoir-search" />
                        </template>
                    </el-input>
                </div>
                <el-popover placement="bottom-end" :width="isBetweenTime ? 700 : 550" trigger="click">
                    <template #reference>
                        <div class="more-search ml-1">
                            <span>更多搜索</span>
                            <i class="i-iconoir-nav-arrow-down" />
                        </div>
                    </template>
                    <div class="hc-alert-tip hc-flex">
                        <i class="i-iconoir-info-circle-solid" />
                        <span>支持模糊搜索，可选择多个搜索条件组合查询，最多可同时设置4个搜索条件</span>
                    </div>
                    <div class="hc-more-search-form" :class="isBetweenTime ? 'is-date-bar' : ''">
                        <el-form :model="searchForm" label-position="left" label-width="auto" class="w-full">
                            <el-form-item label="保管期限">
                                <el-checkbox :checked="isDuration" @change="isDurationChange">不限</el-checkbox>
                                <el-checkbox-group v-model="duration" class="ml-6" :disabled="isDuration" @change="durationChange">
                                    <el-checkbox value="3">永久</el-checkbox>
                                    <el-checkbox value="2">30年</el-checkbox>
                                    <el-checkbox value="1">10年</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item label="案卷档号">
                                <el-input v-model="searchForm.num" clearable />
                            </el-form-item>
                            <el-form-item label="案卷题名">
                                <el-input v-model="searchForm.title" clearable />
                            </el-form-item>
                            <el-form-item label="日期范围" class="date-form-item">
                                <hc-date-picker :dates="betweenTime" clearable :teleported="false" @change="betweenTimeUpdate" @focus="isBetweenTime = true" @blur="isBetweenTime = false" />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="hc-more-search-btn">
                        <el-button hc-btn color="#1890FF" @click="searchBtnClick">搜索</el-button>
                        <el-button hc-btn type="warning" @click="resetSearchClick">重置</el-button>
                    </div>
                </el-popover>
            </template>
            <template #extra>
                <el-button hc-btn @click="toHomePage">返回主页</el-button>
            </template>
            <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :is-index="false" is-new @row-click="tableRowClick">
                <template #title="{ row }">
                    <div @click.stop="tableRowTitle(row)">{{ row?.title }}</div>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>
        <!-- 卷内文件 -->
        <hc-new-drawer v-model="isFileRollDrawer" to-id="hc-layout-main" direction="btt" modal-class="hc-query-file-roll-drawer">
            <QueryFileRoll :datas="fileRollRow" @close="fileRollDrawerClose" />
        </hc-new-drawer>
        <!-- 预览PDF -->
        <hc-new-drawer v-model="isFilePdfDrawer" to-id="hc-layout-main" direction="btt">
            <QueryFilePdf :datas="fileRollPdfData" :rows="fileRollPdfRow" @close="filePdfDrawerClose" />
        </hc-new-drawer>
    </hc-body>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { sql_count, sql_table } from '../utils/dbConnect'
import { getArrValue, isNullES } from 'js-fast-way'
import QueryFileRoll from '../components/query/file-roll.vue'
import QueryFilePdf from '../components/query/file-pdf.vue'
import { toPage } from '../utils/tools'

//初始组合式
const store = useAppStore()

defineOptions({
    name: 'HcQuery',
})

//项目信息
const projectInfo = ref(store.projectInfo)
const projectId = ref('')

onMounted(() => {
    projectInfo.value = store.projectInfo
    projectId.value = store.projectInfo?.key ?? ''
})

//树配置
const treeProps = {
    label: 'label',
    children: 'children',
    isLeaf: 'isLeaf',
}

//数懒加载
const treeLoadNode = async ({ item, level }, resolve) => {
    const parentId = level !== 0 ? item.id ?? 0 : 0
    const { code, data } = await sql_table(`SELECT (id||"") as "id",m1.node_name as "label",(select CASE WHEN COUNT(1)>0 THEN "true" ELSE "false" END FROM m_archive_tree_contract m2 WHERE m2.parent_id = m1.id)as isLeaf FROM m_archive_tree_contract m1 where parent_id = ${parentId}`)
    if (code !== 200 || data.length <= 0) {
        return resolve([])
    }
    const datas = getArrValue(data)
    for (let i = 0; i < datas.length; i++) {
        datas[i].isLeaf = !datas[i].isLeaf
    }
    return resolve(datas)
}

//节点被点击
const treeItem = ref({})
const treeNodeTap = ({ data }) => {
    treeItem.value = data
    searchForm.value.nodeId = data.id
    searchBtnClick()
}

//搜索表单
const searchForm = ref({
    nodeId: null, title:'', duration: '1,2,3',
    num: '', start_time: '', end_time: '',
    current: 1, size: 10, total: 0,
})

//保管期限
const duration = ref(['1', '2', '3'])
const durationChange = () => {
    if (duration.value.length <= 0) {
        searchForm.value.duration = ''
        return
    }
    searchForm.value.duration = duration.value.join(',')
}

//不限保管期限
const isDuration = ref(true)
const isDurationChange = (val) => {
    isDuration.value = val
    if (!val) return
    nextTick(() => {
        duration.value = ['1', '2', '3']
        searchForm.value.duration = '1,2,3'
    })
}

//日期时间被选择
const isBetweenTime = ref(false)
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr }) => {
    isBetweenTime.value = false
    betweenTime.value = arr
    searchForm.value.start_time = arr[0]
    searchForm.value.end_time = arr[1]
}

//回车搜索
const queryEvent = ({ key }) => {
    if (key !== 'Enter') {
        return
    }
    searchBtnClick()
}

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

//重置
const resetSearchClick = () => {
    betweenTime.value = null
    isDuration.value = true
    duration.value = ['1', '2', '3']
    searchForm.value.duration = '1,2,3'
    searchForm.value.num = ''
    searchForm.value.title = ''
    searchForm.value.start_time = ''
    searchForm.value.end_time = ''
}

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

//表格数据
const tableColumn = ref([
    { key: 'number', name: '档号' },
    { key: 'title', name: '案卷题名' },
    { key: 'time', name: '保管期限', width: '80' },
    { key: 'secret', name: '密级', width: '80' },
    { key: 'unit', name: '立卷单位' },
    { key: 'startendtime', name: '文件起止日期' },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const form = searchForm.value
    const title = isNullES(form.title) ? '%' : `%${form.title}%`
    const num = isNullES(form.num) ? '%' : `%${form.num}%`
    //查询表格数据
    const sql1 = `SELECT u.id,u.file_number as number,u.name as title,case u.storage_time when 1 then "10年" when 2 then "30年" else "永久" end as time,case u.secret_level when 1 then "机密" when 2 then "绝密" else "秘密" end as secret,u.unit as unit,(strftime("%Y/%m/%d",u.start_date)||"~"||strftime("%Y/%m/%d",u.end_date)) as startendtime,u.all_file_pdf as allFilePdf FROM u_archives_auto u WHERE storage_time in (${form.duration}) ${form.start_time && form.end_time ? 'and ' + form.start_time + ' < end_date  and ' + form.end_time + ' > start_date' : ''} and node_id in (select id FROM m_archive_tree_contract WHERE (ancestors like '%${form.nodeId}%' or id = '${form.nodeId}')) and u.name like '${title}' and u.file_number like '${num}' order by u.tree_sort,u.file_number asc LIMIT ${form.size} OFFSET ${(form.current - 1) * form.size}`
    const { code: code1, data: data1 } = await sql_table(sql1)
    tableData.value = code1 === 200 ? getArrValue(data1) : []
    //查询总数
    const sql2 = `SELECT count(*) as count FROM u_archives_auto u WHERE storage_time in  (${form.duration}) ${form.start_time && form.end_time ? 'and ' + form.start_time + ' < end_date  and ' + form.end_time + ' > start_date' : ''} and node_id in (select id FROM m_archive_tree_contract WHERE (ancestors like '%${form.nodeId}%' or id = '${form.nodeId}')) and u.name like '${title}' and u.file_number like '${num}'`
    const { code: code2, data: data2 } = await sql_count(sql2)
    searchForm.value.total = code2 === 200 ? data2 ?? 0 : 0
    tableLoading.value = false
}

//案卷题名被点击
const isFilePdfDrawer = ref(false)
const fileRollPdfData = ref([])
const fileRollPdfRow = ref({})
const tableRowTitle = async (row) => {
    //查询表格数据
    const sql = `select id,file_number as number,file_name as title,pdf_file_url as url,file_time as startime,duty_user as dutyUser from u_archive_file where archive_id = '${row.id}'`
    const { code, data } = await sql_table(sql)
    const res = code === 200 ? getArrValue(data) : []
    if (res.length <= 0) {
        fileRollPdfRow.value = {}
    } else {
        fileRollPdfRow.value = res[0]
    }
    fileRollPdfData.value = res
    await nextTick(() => {
        isFilePdfDrawer.value = true
    })
}

//关闭抽屉
const filePdfDrawerClose = () => {
    isFilePdfDrawer.value = false
    fileRollPdfRow.value = {}
    fileRollPdfData.value = []
}


//单击行
const isFileRollDrawer = ref(false)
const fileRollRow = ref({})
const tableRowClick = ({ row }) => {
    fileRollRow.value = row
    isFileRollDrawer.value = true
}

//关闭抽屉
const fileRollDrawerClose = () => {
    isFileRollDrawer.value = false
    fileRollRow.value = {}
}

//返回主页
const toHomePage = () => {
    toPage({ page: '/home' })
}
</script>

<style lang="scss">
@import '../styles/query';
</style>
