<template>
    <div class="hc-page-layout-box" id="carry-spot-checks-layout-target">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'"  v-show="!isCarrySpotChecksDrawer">
            <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="projectTreeClick" @nodeLoading="treeNodeLoading" :autoExpandKeys="treeAutoExpandKeys" @menuTap="ElTreeMenuClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box" v-show="!isCarrySpotChecksDrawer">
            <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-target" @close="onCarrySpotChecksDrawerClose">
            <div class="hc-carry-spot-checks-pdf">
                <HcPdf :src="pdfUrl" v-loading="pdfLoading"/>
                <el-tooltip content="展开/收起 右侧目录" placement="top" :disabled="!isBubble">
                    <div class="hc-csc-pdf-btn" @click="onCarryDataShow">
                        <HcIcon name="arrow-right-s" v-show="isCarryDataShow"/>
                        <HcIcon name="arrow-left-s" v-show="!isCarryDataShow"/>
                    </div>
                </el-tooltip>
            </div>
            <div class="hc-carry-spot-checks-data" v-show="isCarryDataShow">
                <div class="hc-csc-switch">
                    <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange" size="default" :round="false"/>
                </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 class="content" v-if="fileInfo?.endDate!==''||fileInfo?.startDate!==''">{{ splitDate(fileInfo?.startDate)+"~"+  splitDate(fileInfo?.endDate)}}</div>
                            <div class="content" v-else></div>
                        </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 :column="cscTableColumn1" :datas="cscTableData1" :loading="cscTableLoading" :isArrIndex="false" v-if="tabTypeKey === 'tab1'">
                        <template #name="{row}">
                            <div :class="row.id === checkId ? 'text-link' : 'text-hover'" @click="changePdf(row)">{{row?.fileName}}</div>
                        </template>
                    </HcTable>

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

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

                    <HcTable :column="cscTableColumn4" :datas="cscTableData4" :loading="cscTableLoading" :isIndex="false" v-if="tabTypeKey === 'tab4'">
                        <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 :loading="cscTableLoading" v-if="tabTypeKey === 'tab5'"/>

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

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

        <!--使用弹窗查看数据-->
        <HcDialog :show="cscTableDataModal" :title="cscTableDataTitle" widths="1080px" isTable :footer="false" @close="cscTableDataModalClose">
            <MetaTable :loading="cscTableLoading" v-if="tabTypeKey === 'tab5'"/>
            <HcTable :column="cscTableColumn51" :datas="cscTableData5" :loading="cscTableLoading" v-if="tabTypeKey === 'tab6'"/>
        </HcDialog>

    </div>
</template>

<script setup>
import {ref, watch, onMounted, nextTick,onActivated} 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 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 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: '档号'},
        {key: 'name', name: '案卷题名', width: 500},
        {key: 'storageTimeValue', name: '保管期限'},
        {key: 'pageN', name: '总页数'},
        {key:'unit', name: '立卷单位', width: 150},
        {key:'remark', name: '备注', width: 150}
    ]
}
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 splitDate=(val)=>{
    
    return val.substring( 0,10)
}
//查阅案卷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 tableRowClick = async({row}) => {
    //console.log(row)
    fileInfo.value=row
    fileInfo.value.pageNumber=row['approvalFileList'].length||0
    cscTableData1.value=getArrValue( row['approvalFileList'])
    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 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');
    pdfLoading.value=false
    pdfUrl.value=row['pdfFileUrl']||''
    checkId.value=row.id
    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
}

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 = '元数据'
    } else if (key === 'tab6') {
        cscTableDataTitle.value = '验签包'
    }
    cscTableDataModal.value = true
}

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


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


//左右拖动，改变树形结构宽度
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;
    }
}
</script>

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

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

</style>
