<template>
    <div id="carry-spot-checks-layout-target1" class="hc-page-layout-box">
        <div v-show="!isCarrySpotChecksDrawer" 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 v-loading="treeLoading" class="hc-tree-box" element-loading-text="加载中...">
                <el-scrollbar>
                    <HcTree :project-id="projectId" :contract-id="contractId" :auto-expand-keys="treeAutoExpandKeys" @nodeTap="projectTreeClick" @nodeLoading="treeNodeLoading" @menuTap="ElTreeMenuClick" />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div v-show="!isCarrySpotChecksDrawer" class="hc-page-content-box">
            <HcCard title="已形成的案卷">
                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" @row-click="tableRowClick">
                    <template #name="{ row }">
                        <div class="text-link" :class="row.isReviewed === 1 ? 'text-green' : 'text-blue'">
                            {{ row?.name }}
                        </div>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcCard>
        </div>

        <!-- 展开抽查 -->
        <HcDrawer :show="isCarrySpotChecksDrawer" uis="hc-carry-spot-checks-target" to-id="carry-spot-checks-layout-target1" @close="onCarrySpotChecksDrawerClose">
            <div class="hc-carry-spot-checks-pdf">
                <HcPdf v-loading="pdfLoading" :src="pdfUrl" />
                <el-tooltip content="展开/收起 右侧目录" placement="top" :disabled="!isBubble">
                    <div class="hc-csc-pdf-btn" @click="onCarryDataShow">
                        <HcIcon v-show="isCarryDataShow" name="arrow-right-s" />
                        <HcIcon v-show="!isCarryDataShow" name="arrow-left-s" />
                    </div>
                </el-tooltip>
            </div>
            <div v-show="isCarryDataShow" class="hc-carry-spot-checks-data">
                <div class="hc-csc-switch">
                    <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" size="default" :round="false" @change="tabTypeChange" />
                </div>
                <div class="hc-csc-info-box">
                    <el-scrollbar>
                        <div class="hc-info-text-item">
                            <div class="title">
                                案卷题名：
                            </div>
                            <div class="content">
                                {{ fileInfo.name }}
                            </div>
                        </div>
                        <div class="hc-info-text-item">
                            <div class="title">
                                <span>密</span>
                                <span class="ml-7">级：</span>
                            </div>
                            <div class="content">
                                {{ fileInfo.secretLevelValue }}
                            </div>
                        </div>
                        <div class="hc-info-text-item">
                            <div class="title">
                                保管期限：
                            </div>
                            <div class="content">
                                {{ fileInfo.storageTimeValue }}
                            </div>
                        </div>
                        <div class="hc-info-text-item">
                            <div class="title">
                                卷内文件：
                            </div>
                            <div class="content">
                                {{ fileInfo.pageNumber }}
                            </div>
                        </div>
                        <div class="hc-info-text-item">
                            <div class="title">
                                起止日期：
                            </div>
                            <div v-if="fileInfo?.endDate !== '' || fileInfo?.startDate !== null" class="content">
                                {{ `${splitDate(fileInfo?.startDate)}~${splitDate(fileInfo?.endDate)}` }}
                            </div>
                            <div v-else class="content" />
                        </div>
                        <div class="hc-info-text-item">
                            <div class="title">
                                立卷单位：
                            </div>
                            <div class="content">
                                {{ fileInfo.unit }}
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <div class="hc-csc-data-box" :style="{ height: checkId ? '' : 'calc(100% - 363px)' }">
                    <HcTable v-if="tabTypeKey === 'tab1'" :column="cscTableColumn1" :datas="cscTableData1" :loading="cscTableLoading" :is-arr-index="false">
                        <template #name="{ row }">
                            <div :class="row.id === checkId ? 'text-link' : 'text-hover'" @click="changePdf(row)">
                                {{ row?.fileName }}
                            </div>
                        </template>
                    </HcTable>

                    <HcTable v-if="tabTypeKey === 'tab2'" :column="cscTableColumn2" :datas="cscTableData2" :loading="cscTableLoading" :is-index="false">
                        <template #name="{ row }">
                            <div :class="row.id === 2 ? 'text-link' : 'text-hover'">
                                {{ row?.name }}
                            </div>
                        </template>
                    </HcTable>

                    <HcTable v-if="tabTypeKey === 'tab3'" :column="cscTableColumn3" :datas="cscTableData3" :loading="cscTableLoading" :is-index="false">
                        <template #name="{ row }">
                            <div :class="row.id === 2 ? 'text-link' : 'text-hover'">
                                {{ row?.name }}
                            </div>
                        </template>
                    </HcTable>

                    <HcTable v-if="tabTypeKey === 'tab4'" :column="cscTableColumn4" :datas="cscTableData4" :loading="cscTableLoading" :is-index="false">
                        <template #name="{ row }">
                            <div class="hc-csc-associated-row" :class="row.id === 2 ? 'text-link' : 'text-hover'">
                                <el-tag effect="dark">
                                    {{ row?.tag }}
                                </el-tag>
                                <span class="ml-3">{{ row?.name }}</span>
                            </div>
                        </template>
                    </HcTable>

                    <MetaTable v-if="tabTypeKey === 'tab5'" :loading="cscmetaTableLoading" :meta-data-table="cscmetaDataTabledata" :ishow-file="ishowFile" />
                 

                    <HcTable v-if="tabTypeKey === 'tab6'" :column="cscTableColumn5" :datas="cscTableData5" :loading="cscTableLoading" />

                    <el-tooltip v-if="tabTypeKey === 'tab6' || tabTypeKey === 'tab5'" content="使用弹窗查看数据" placement="top" :disabled="!isBubble">
                        <div class="hc-table-info-btn" @click="cscTableDataModalShow">
                            <HcIcon name="airplay" />
                        </div>
                    </el-tooltip>
                </div>
                <div v-if="checkId" class="hc-csc-action-box">
                    <div class="header-box">
                        <div class="title">
                            抽检意见：
                        </div>
                        <div class="extra">
                            <el-checkbox v-model="reform.type" class="size-xl">
                                需要整改
                            </el-checkbox>
                        </div>
                    </div>
                    <div class="textarea-box">
                        <div v-if="ishowAllopinion" @click="contentClick">
                            <el-input v-model="reform.content" type="textarea" :autosize="{ minRows: 5 }" resize="none" placeholder="请填写抽检意见" />
                        </div>
                        <div v-else>
                            <el-input v-model="reform.myOpinion" type="textarea" :autosize="{ minRows: 5 }" resize="none" placeholder="请填写抽检意见" />
                        </div>
                    </div>
                    <div class="btn-box">
                        <el-button hc-btn @click="onCarrySpotChecksDrawerClose">
                            <HcIcon name="close" />
                            <span>取消查阅</span>
                        </el-button>
                        <el-button type="primary" hc-btn :loading="submitLoading" :disabled="ishowAllopinion" @click="submitOpinion">
                            <HcIcon name="check" />
                            <span>保存抽检意见</span>
                        </el-button>
                    </div>
                </div>
                <div v-if="checkId.length == 0" class="btn-box" style="text-align: center;">
                    <el-button hc-btn @click="onCarrySpotChecksDrawerClose">
                        <HcIcon name="close" />
                        <span>取消查阅</span>
                    </el-button>
                </div>
            </div>
        </HcDrawer>

        <!-- 使用弹窗查看数据 -->
        <HcDialog :show="cscTableDataModal" :title="cscTableDataTitle" widths="1080px" is-table :footer="false" @close="cscTableDataModalClose">
            <MetaTable v-if="tabTypeKey === 'tab5'" :loading="cscmetaTableLoading" :meta-data-table="cscmetaDataTabledata" :ishow-file="ishowFile" />
            <HcTable v-if="tabTypeKey === 'tab6'" :column="cscTableColumn51" :datas="cscTableData5" :loading="cscTableLoading" />
        </HcDialog>
    </div>
</template>

<script setup>
import { nextTick, onActivated, onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { getArrValue, getObjValue } from 'js-fast-way'
import HcTree from '~src/components/tree/hc-tree.vue'
import MetaTable from './components/meta-table.vue'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import tuningApi from '~api/archiveConfig/tuning.js'
import archiveQueryApi from '~api/using/query.js'
import inspectApi from '~api/transfer/inspects.js'

//变量

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const isCollapse = ref(useAppState.getCollapse)
const isBubble = ref(useAppState.getBubble)
const userInfo = ref(useAppState.getUserInfo)

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

//渲染完成
onMounted(() => {
    setTableColumns()
})
//缓存被激活时
onActivated(() => {
    getTableData()
})
//树加载
const treeLoading = ref(true)
const treeNodeLoading = () => {
    treeLoading.value = false
}

//搜索表单
const searchForm = ref({
    current: 1, size: 20, total: 0,
})
//截取日期
const splitDate = (val)=>{
    if (val) {
        return val?.substring(0, 10)
    } else {
        return ''
    }
}
//树相关的变量
const primaryKeyId = ref('')

//自动展开缓存
const treeAutoExpandKeys = ref(getStoreValue('inspectExpandKeys') || [])
const projectTreeClick = ({ node, data, keys, key }) => {
    console.log(data)
    //缓存展开的节点
    setStoreValue('inspectExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []

    searchForm.value.total = 0
    searchForm.value.current = 1
    searchForm.value.size = 20
    searchForm.value.nodeIds = data.id || ''
    getTableData()
}
//树菜单被点击
const ElTreeMenuClick = async ({ key, node, data }) => {

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

//表格数据
const tableRef = ref(null)
const tableColumn = ref([])
//设置表头
const setTableColumns = () => {
    tableColumn.value = [
        { key: 'fileNumber', name: '档号', width:110 },
        { key: 'name', name: '案卷题名' },
        { key: 'storageTimeValue', name: '保管期限', width:100 },
        { key: 'pageN', name: '总页数', width:110 },
        { key:'unit', name: '立卷单位', width: 140 },
        { key:'remark', name: '备注', width: 110 },
    ]
}
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
    }
}

//查阅案卷pdf
const viewPdf = async (id) => {
    window.$message?.info('预览案卷需要合并pdf，需要一点时间')
    pdfLoading.value = true
    const { error, code, data, msg } = await tuningApi.printArchive({
        id: id,
    })
    pdfLoading.value = false
    if (!error && code === 200) {
        if (data) {
            return data
        } else {
            window.$message?.warning('文件不存在')
        }
    } 
}
//行被点击
const isCarrySpotChecksDrawer = ref(false)
const fileInfo = ref('')
const checkmetaFileId = ref('')
const tableRowClick = async ({ row }) => {
    //console.log(row)
    fileInfo.value = row
    // cscTableData1.value=getArrValue( row['approvalFileList'])
    getArchiveFileListData()
    isCarrySpotChecksDrawer.value = true
    ishowAllopinion.value = true
    checkId.value = ''
  
   
    const url = await viewPdf(row.id)
        pdfUrl.value = url
        if (pdfUrl.value && pdfUrl?.value.length > 0 && isCarrySpotChecksDrawer.value) {
            setTimeout(() => {
                 serReviewFile()
            }, 20000)
        }
}
//获取卷内文件数据
const getArchiveFileListData = async ()=>{
    const { error, code, msg, data } = await archiveQueryApi.getArchiveFileList({
        id: fileInfo.value.id, //案卷id
     
    })
    //处理返回数据
    if (!error && code === 200) {
        fileInfo.value.pageNumber = data.pageNumber 
        
        cscTableData1.value = getArrValue(data['approvalFileList']) 
        if (cscTableData1.value.length > 0) {
            checkmetaFileId.value = cscTableData1.value[0].id
            getmetaInfo()
        }

    } else {
       
        cscTableData1.value = []
    }
}
//设置为已查阅
const serReviewFile = async ()=>{
            const { error, code, data, msg } = await inspectApi.setreview({
                id: fileInfo.value.id,
            })
}
const checkId = ref('')
const pdfUrl = ref('')
const pdfLoading = ref(false)
const changePdf = (row)=>{
    console.log(row, 'row')
    ishowFile.value = true
    pdfLoading.value = false
    pdfUrl.value = row['pdfFileUrl'] || ''
    checkId.value = row.id
    checkmetaFileId.value = row.id
    getmetaInfo()
    ishowAllopinion.value = true

    getopiniondata()
    if (pdfUrl.value && pdfUrl?.value.length > 0 && isCarrySpotChecksDrawer.value) {
            setTimeout(() => {
                 serReviewFile()
            }, 20000)
     }


}
const opid = ref('')

//获取抽检意见
const getopiniondata = async ()=>{
    const { error, code, data, msg } = await inspectApi.getOpinion({
        fileId: checkId.value,
    })
    if (!error && code === 200) {
        console.log(data, 'data')
        let opiniondata = getObjValue(data)
        reform.value.content = opiniondata?.allOpinion
        reform.value.type = opiniondata?.allOpinion?.length > 0 ? true : false
        reform.value.myOpinion = opiniondata?.opinion
        opid.value = opiniondata?.id
    } 
}
//保存抽检意见
const submitLoading = ref(false)
const submitOpinion = async ()=>{
    submitLoading.value = true
    const { error, code, data, msg } = await inspectApi.addOpinion({
        fileId: checkId.value,
        archiveId:fileInfo.value.id,
        // opinion:reform.value.content,
        opinion:reform.value.myOpinion,
        projectId:projectId.value,
        userId:userInfo.value.user_id,
        archiveName:fileInfo.value.name,
        id:  opid.value || null,

    })
    submitLoading.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        serReviewFile()
        getTableData()
      
    } 
    // addOpinion
}
//类型tab数据和相关处理
const tabTypeKey = ref('tab1')
const tabTypeTab = ref([
    { key:'tab1', name: '卷内文件' },
    { key:'tab2', name: '竣工资料' },
    { key:'tab3', name: '计量资料' },
    { key:'tab4', name: '关联资料' },
    { key:'tab5', name: '元数据' },
    { key:'tab6', name: '验签包' },
])
const tabTypeChange = ({ key }) => {
    tabTypeKey.value = key
    if (key === 'tab5') {
        // getmetaInfo()
        if (ishowFile.value) {
            getmetaInfo()
        } else {
            getArchivesAutoView(fileInfo.value.id)
        }

    }
}
//获取案卷元数据信息
const getArchivesAutoView = async (fileId)=>{
    cscmetaTableLoading.value = true
    const { error, code, data } = await tuningApi.getArchivesAutoView({
        id:fileId,
    })
    cscmetaTableLoading.value = false
    if (!error && code === 200) {
        let obj = getObjValue(data)
        cscmetaDataTabledata.value = [
            { containerName:'题名', keyValue:'', isType:3 },
            { containerName:'档号', keyValue:obj?.fileNumber, isType:2 },
            { containerName:'文件件数', keyValue:obj?.fileN, isType:2 },
            { containerName:'移交时间', keyValue:'', isType:2 },
        ]
    } else {
        cscmetaDataTabledata.value = []
    }
}
const cscTableLoading = ref(false)

//卷内目录
const cscTableColumn1 = [
    { key:'name', name: '卷内文件题名', align: 'center' },
]
const cscTableData1 = ref([

])

//竣工资料
const cscTableColumn2 = [
    { key:'name', name: '竣工图资料', align: 'center' },
]
const cscTableData2 = ref([
    // {id: 1, name: 'S6-3-2-Q-8-32 箱梁梁底支座垫石钢筋构造图111-箱梁梁底调平垫块及支座垫石钢筋构造图.pdf'},
    // {id: 2, name: 'J6-3-2-Q-8-34 桥墩一般构造图(1-9).pdf'},
    // {id: 3, name: 'S6-3-2-Q-8-32 箱梁梁底支座垫石钢筋构造图111-箱梁梁底调平垫块及支座垫石钢筋构造图.pdf'},
    // {id: 4, name: 'J6-3-2-Q-8-34 桥墩一般构造图(1-9).pdf'},
    // {id: 5, name: 'J6-3-2-Q-8-34 桥墩一般构造图(1-9).pdf'},
    // {id: 6, name: 'S6-3-2-Q-8-32 箱梁梁底支座垫石钢筋构造图111-箱梁梁底调平垫块及支座垫石钢筋构造图.pdf'},
    // {id: 7, name: 'S6-3-2-Q-8-32 箱梁梁底支座垫石钢筋构造图111-箱梁梁底调平垫块及支座垫石钢筋构造图.pdf'}
])

//计量资料
const cscTableColumn3 = [
    { key:'name', name: '计量资料', align: 'center' },
]
const cscTableData3 = ref([
    // {id: 1, name: 'ZB2-17.pdf'},
    // {id: 2, name: 'ZB2-18.pdf'},
    // {id: 3, name: 'ZB2-19.pdf'},
    // {id: 4, name: 'ZB2-20.pdf'},
    // {id: 5, name: 'ZB2-21.pdf'},
    // {id: 6, name: 'ZB2-22.pdf'},
    // {id: 7, name: 'ZB2-23.pdf'}
])

//计量资料
const cscTableColumn4 = [
    { key:'name', name: '关联文件', align: 'center' },
]
const cscTableData4 = ref([
    // {id: 1, name: 'xxxxxxxxxxxxxxxxxxx.pdf', tag: '开工'},
    // {id: 2, name: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.pdf', tag: '工序'},
    // {id: 3, name: 'xxxxxxxxxxxxxxxxxxxxxxxxxx.pdf', tag: '评定'},
    // {id: 4, name: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx.pdf', tag: '交工'},
    // {id: 5, name: '', tag: '抽检'},
    // {id: 6, name: '', tag: '隐蔽'}
])


//验签包
const cscTableColumn5 = [
    { key:'user', name: '签名者' },
    { key:'time', name: '签名时间' },
    { key:'val', name: '摘要' },
]
const cscTableColumn51 = [
    { key:'user', name: '签名者', width: 300 },
    { key:'time', name: '签名时间', width: 200 },
    { key:'val', name: '摘要' },
]
const cscTableData5 = ref([
    // {id: 1, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'},
    // {id: 2, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'},
    // {id: 3, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'},
    // {id: 4, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'},
    // {id: 5, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'},
    // {id: 6, user: '051@王海军@0422431197502148151@1', time: '2022-05-13 08:54:15', val: '签名有效。由051@王海军@0422431197502148151@1签名。自应用本签名以来，文档未被修改过。签名者身份有效。'}
])


//抽检意见
const reform = ref({
    type: false, content: '', myOpinion:'',
})
const ishowAllopinion = ref(true)
const contentClick = ()=>{
    console.log(11111)
    ishowAllopinion.value = false
}
//显示右侧目录
const isCarryDataShow = ref(true)
const onCarryDataShow = () => {
    isCarryDataShow.value = !isCarryDataShow.value
}


//使用弹窗查看数据
const cscTableDataModal = ref(false)
const cscTableDataTitle = ref('')
//显示弹窗
const cscTableDataModalShow = () => {
    const key = tabTypeKey.value
    if (key === 'tab5') {
        cscTableDataTitle.value = '元数据'
        // getmetaInfo()
        if (ishowFile.value) {
            getmetaInfo()
        } else {
            getArchivesAutoView(fileInfo.value.id)
        }
    } else if (key === 'tab6') {
        cscTableDataTitle.value = '验签包'
    }
    cscTableDataModal.value = true
}

//关闭弹窗
const cscTableDataModalClose = () => {
    cscTableDataModal.value = false
    getTableData()
}


//关闭抽查
const onCarrySpotChecksDrawerClose = () => {
    isCarrySpotChecksDrawer.value = false
    pdfUrl.value = ''
    ishowFile.value = false
    checkmetaFileId.value = ''
    tabTypeKey.value = 'tab1'
}


//左右拖动，改变树形结构宽度
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 cscmetaTableLoading = ref(false)
const cscmetaDataTabledata = ref([])
const ishowFile = ref(false)
//获取元数据信息

const getmetaInfo = async (fileId)=>{
 
    cscmetaTableLoading.value = true
    const { error, code, data } = await tuningApi.getMetadataFileByid({
        fileId: checkmetaFileId.value,
    })
    cscmetaTableLoading.value = false
    if (!error && code === 200) {
        cscmetaDataTabledata.value = getArrValue(data)
    } else {
        cscmetaDataTabledata.value = []
    }
}
</script>

<style lang="scss" scoped>
@import '~style/transfer/scoped/inspects.scss';
</style>

<style lang="scss">
@import '~style/transfer/inspects.scss';
@import '../../styles/theme/transfer/inspect.scss';
</style>
