<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>
                    <TestTree
                        :autoExpandKeys="treeAutoExpandKeys"
                        :projectId="projectId"
                        :wbsTempId="projectInfo?.referenceWbsTemplateIdTrial"
                        :wbsType="2"
                        :tenantId="userInfo?.tenant_id"
                        @nodeTap="wbsElTreeClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard :scrollbar="false" actionSize="lg">
                <template #header>
                    <HcTooltip keys="tentative_detect_test_add">
                        <el-button type="primary" hc-btn :disabled="!primaryKeyId" @click="addFormModalClick">
                            <HcIcon name="add-circle"/>
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_detect_test_copy">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="copyLoading" @click="copyDataClick">
                            <HcIcon name="file-copy-2"/>
                            <span>复制</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_detect_test_del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="removeLoading" @click="delModalClick">
                            <HcIcon name="delete-bin-2"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_detect_test_print">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printPdfLoading" @click="printPdfClick">
                            <HcIcon name="printer"/>
                            <span>批量打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_detect_test_null">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printNullPdfLoading" @click="printNullPdfClick">
                            <HcIcon name="printer"/>
                            <span>打印空表</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #extra>
                    <el-button :type="authBtnTabKey === '1'?'primary':''" hc-btn @click="authBtnTabClick('1')">
                        <HcIcon name="folder-user"/>
                        <span>施工自检</span>
                    </el-button>
                    <el-button :type="authBtnTabKey === '2'?'primary':''" hc-btn @click="authBtnTabClick('2')">
                        <HcIcon name="folder-shield"/>
                        <span>监理质检</span>
                    </el-button>
                </template>
                <template #search>
                    <div class="w-40">
                        <el-input v-model="searchForm.trialUserName" placeholder="请输入试验人员" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="w-40 ml-2">
                        <el-select v-model="searchForm.queryStatus" placeholder="请选择是否合格" clearable>
                            <el-option v-for="item in qualifiedData" :key="item.value" :label="item['label']" :value="item['value']"/>
                        </el-select>
                    </div>
                    <div class="w-64 ml-2">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                    </div>
                    <div class="w-72 ml-2">
                        <el-input v-model="searchForm.queryValue" placeholder="请输入项目名称关键字" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2"/>
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection">
                    <template #recordNo="{row}">
                        <span class="text-link" @click="tableRowEdit(row,'1')">{{row?.recordNo}}</span>
                    </template>
                    <template #reportNo="{row}">
                        <span class="text-link" @click="tableRowEdit(row,'2')">{{row?.reportNo}}</span>
                    </template>
                    <template #trialProjectName="{row}">
                        <span class="text-link font-bold" @click="tableRowPdf(row)">{{row?.trialProjectName}}</span>
                    </template>
                    <template #taskStatus="{row}">
                        <el-tag :type="`${row.status === 2 ? 'success' : row.status === 0 ? 'warning' : row.status === 1 ? 'danger' : 'info'}`"
                                class="mx-1" effect="dark" v-if="row['taskStatus']">{{row['taskStatus']}}</el-tag>
                    </template>
                    <template #detectionCategory="{row}">
                        <span>{{getArrKeyValue(categoryData, 'dictKey', 'dictValue', row.detectionCategory)}}</span>
                    </template>
                    <template #isUploadCertificate="{row}">
                        <span>{{row.isUploadCertificate == 0 ? '是' : '否'}}</span>
                    </template>
                    <template #contractId="{row}">
                        <span>{{contractInfo?.name}}</span>
                    </template>
                    <template #detectionResult="{row}">
                        <span>{{row.detectionResult == 1 ? '合格' : '不合格'}}</span>
                    </template>
                    <template #action="{row}">
                        <HcTooltip keys="tentative_detect_test_annex">
                            <el-button type="primary" size="small" plain   @click="viewAttachmentModalClick(row)">附件</el-button>
                        </HcTooltip>
                        <HcTooltip keys="tentative_detect_test_info">
                            <el-button type="primary" size="small" plain @click="samplingRecordModalClick(row)">样品信息</el-button>
                        </HcTooltip>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--查看附件-->
        <HcDialog :show="viewAttachmentModal" title="查看附件" widths="70rem" :footer="false" isTable @close="viewAttachmentModalClose">
            <template #extra>
                <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange"/>
            </template>
            <div class="hc-switch-tab-content" v-loading="viewAttachmentLoading">
                <div class="h-full w-full flex">
                    <div class="pdf-file-list-box">
                        <template v-for="item in viewAttachmentData" >
                            <div class="file-item" :class="[item.isCheck ? 'cur' : '']"  @click="viewCurFile(item)">{{item.name||''}}</div>
                        </template>
                        <!-- <div class="file-item">文件名称2.pdf</div>
                        <div class="file-item">文件名称3.pdf</div>
                        <div class="file-item">文件名称4.pdf</div>
                        <div class="file-item">文件名称5.pdf</div> -->
                    </div>
                   <!-- <iframe width='80%' height='100%' frameborder='1' :src="attachmentPdfUrl" v-if="attachmentPdfUrl"/> -->
                    <div class="hc-no-table-form" >
                        <div class="table-form-no">
                            <HcDragUpload  @progress="uploadprogress" @finished="uploadFinished" :datas="uploadData"  :fileList="fileListData" v-if="listuploadref==='1'"/>
                             <HcDragUpload  @progress="uploadprogress" @finished="uploadFinished" :datas="uploadData"  :fileList="fileListData" v-if="listuploadref==='2'"/>
                             <HcDragUpload  @progress="uploadprogress" @finished="uploadFinished" :datas="uploadData"  :fileList="fileListData" v-if="listuploadref==='3'"/>
                        </div>
                    </div>
                </div>
            </div>
        </HcDialog>

        <!--查看样品信息-->
        <HcDialog :show="samplingRecordModal" title="查看样品信息" widths="60%" :footer="false" isTable @close="samplingRecordModalClose">
            <HcTable :column="samplingTableColumn" :datas="samplingTableData" :loading="samplingTableLoading" :isIndex="false"></HcTable>
        </HcDialog>

    </div>
</template>

<script setup>
import {ref, watch, onMounted} from "vue";
import {useRouter} from 'vue-router'
import {useAppStore} from "~src/store";
import TestTree from "../material/components/TestTree.vue"
import {getStoreData, setStoreData, delStoreData} from '~src/utils/storage'
import {getArrValue, getArrKeyValue, isString} from "vue-utils-plus";
import HcDragUpload from "./components/HcDragUpload.vue"
import dataApi from "~api/tentative/detect/test";
import {delMessage, rowsToId} from "~uti/tools";
import {getDictionary} from "~api/other";

//变量
const router = useRouter()
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo);
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const contractInfo = ref(useAppState.getContractInfo);
const isCollapse = ref(useAppState.getCollapse)
const isBubble = ref(useAppState.getBubble);

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

//获取气泡数据
const getButtonsVal = (value) => {
    return useAppState.getButtonsVal(value)
}

//自动展开缓存
const treeAutoExpandKeys = ref(getStoreData('testTreeExpandKeys') || [])
const btn_edit = ref(false)

//渲染完成
onMounted(() => {
    btn_edit.value = getButtonsVal('tentative_detect_test_edit')
    setContractType(contractInfo.value?.contractType)
    getCategoryData()
})

const qualifiedData = ref([
    {label: '不合格', value: '0'},
    {label: '合格', value: '1'}
])

//获取检测类别类型
const categoryData = ref([])
const getCategoryData = async () => {
    const { data } = await getDictionary({
        code: 'trial_detection_category'
    })
    const arrData = getArrValue(data)
    arrData.forEach(item => {
        item.dictKey = Number(item.dictKey)
    })
    categoryData.value = arrData
}

//搜索表单
const searchForm = ref({
    trialUserName: null, queryStatus: null, queryValue: null, type: '1',
    current: 1, size: 20, total: 0
})

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

//树被点击
const wbsElTreeClick = ({data, keys}) => {
    nodeDataInfo.value = data
    primaryKeyId.value = data['primaryKeyId'] || ''
    setStoreData('testTreeItem',data)
    //缓存自动展开
    treeAutoExpandKeys.value = keys
    setStoreData('testTreeExpandKeys',keys)
    //改变搜索表单数据
    searchForm.value.nodeId = data['primaryKeyId'];
    searchForm.value.current = 1;
    getTableData()
}

//身份按钮切换数据
const authBtnTabKey = ref('1')
const authBtnTabClick = (val) => {
    if (val !== authBtnTabKey.value) {
        authBtnTabKey.value = val
        searchForm.value.type = val;
        searchForm.value.current = 1;
        getTableData()
    }
}
//contractType,  1施工，2监理
const setContractType = (contractType) => {
    let typeValue = '1';
    if (contractType > 0) {
        typeValue = contractType + ''
    }
    authBtnTabKey.value = typeValue
    searchForm.value.type = typeValue
    searchForm.value.current = 1;
}

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({arr}) => {
    betweenTime.value = arr
    if (arr.length > 0) {
        searchForm.value.startTime = arr[0]
        searchForm.value.endTime = arr[1]
    }
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchForm.value.current = 1;
        getTableData()
    }
}

//搜索
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:'recordNo', name: '记录编号', width: 220},
    {key:'reportNo', name: '报告编号', width: 220},
    {key:'samplingLocation', name: '取样地点', width: 220},
    {key:'trialProjectName', name: '试验项目名称', width: 220},
     {key:'taskStatus', name: '任务状态', width: 140},
    {key:'detectionCategory', name: '检测类别', width: 120},
    {key:'isUploadCertificate', name: '是否上传合格证', width: 130},
    {key:'contractId', name: '合同段', width: 220},
    {key:'company', name: '单位', width: 160},
    {key:'specificationNumber', name: '样品编号', width: 220},
    {key:'specificationModel', name: '规格类型', width: 200},
    {key:'detectionResult', name: '检测结果', width: 160},
    //{key:'projectPosition', name: '工程部位及用途', width: 160},
    {key:'projectPositionName', name: '工程部位及用途', width: 160},
    {key:'reportDate', name: '报告日期', width: 170},
    {key:'trialUserName', name: '试验人员', width: 170},
    {key:'action', name: '操作', width: 150, fixed: 'right', align: 'center'},
])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await dataApi.queryPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value
    })
    //处理数据
    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 addFormModalClick = () => {
    delStoreData('test-form')
    router.push({
        path: '/tentative/detect/test-form',
        query: {
            nodeId: primaryKeyId.value,
            dataType: authBtnTabKey.value,
            isaddType:true,
        }
    })
}

//编辑
const tableRowEdit = (row,tabTypeKey) => {
    setStoreData('test-form', row)
    setStoreData('prenodeDataInfo', nodeDataInfo.value)
    console.log(JSON.stringify(nodeDataInfo.value),'JSON.stringify(nodeDataInfo.value)');
    router.push({
        path: '/tentative/detect/test-form',
        query: {
            id: row.id,
            nodeId: row.nodeId,
            dataType: row.type,
            tabTypeKey:tabTypeKey
            // prenodeDataInfo:JSON.stringify(nodeDataInfo.value)

        }
    })
}

//预览PDF
const tableRowPdf = ({pdfUrl}) => {
    if (pdfUrl) {
        window.open(pdfUrl,'_blank')
    } else {
        window.$message?.warning('该数据暂无PDF')
    }
}

//复制
const copyDataClick = () => {
    const rows = tableCheckedKeys.value;
    if (rows.length > 0) {
        const ids = rowsToId(rows)
        copyDataApi(ids)
    } else {
        window.$message?.warning('请先勾选需要复制的记录')
    }
}

//请求复制
const copyLoading = ref(false)
const copyDataApi = async (ids) => {
    //请求数据
    copyLoading.value = true
    const { error, code, msg } = await dataApi.copyData({
        ids: ids
    },false)
    //处理数据
    copyLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('复制成功')
        searchClick()
    } else {
        window.$message?.error(msg)
    }
}

//删除
const delModalClick = () => {
    const rows = tableCheckedKeys.value;
    if (rows.length > 0) {
        delMessage(() => {
            const ids = rowsToId(rows)
            removeDataApi(ids)
        })
    } else {
        window.$message?.warning('请先勾选需要删除的记录')
    }
}

//请求删除
const removeLoading = ref(false)
const removeDataApi = async (ids) => {
    //请求数据
    removeLoading.value = true
    const { error, code, msg } = await dataApi.removeData({
        ids: ids
    },false)
    //处理数据
    removeLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        searchClick()
    } else {
        window.$message?.error(msg)
    }
}

//批量打印
const printPdfLoading = ref(false)
const printPdfClick = async () => {
    const rows = tableCheckedKeys.value;
    if (rows.length > 0) {
        const ids = rowsToId(rows)
        //请求数据
        printPdfLoading.value = true
        const { error, code, msg, data } = await dataApi.printPdf({
            ids: ids
        },false)
        //处理数据
        const pdfUrl = isString(data) ? data || '' : ''
        printPdfLoading.value = false
        if (!error && code === 200 && pdfUrl) {
            window.open(pdfUrl,'_blank')
        } else {
            window.$message?.error(msg || '文件异常')
        }
    } else {
        window.$message?.warning('请先勾选需要批量打印的记录')
    }
}

//打印空表
const printNullPdfLoading = ref(false)
const printNullPdfClick = async () => {
    const rows = tableCheckedKeys.value;
    if (rows.length > 0) {
        const ids = rowsToId(rows)
        //请求数据
        printNullPdfLoading.value = true
        const { error, code, msg, data } = await dataApi.printNullPdf({
            ids: ids
        },false)
        //处理数据
        const pdfUrl = isString(data) ? data || '' : ''
        printNullPdfLoading.value = false
        if (!error && code === 200 && pdfUrl) {
            window.open(pdfUrl,'_blank')
        } else {
            window.$message?.error(msg || '文件异常')
        }
    } else {
        window.$message?.warning('请先勾选需要打印空表的记录')
    }
}

//查看附件
const viewAttachmentModal = ref(false)
const viewAttachmentLoading = ref(false)
const viewAttachmentId = ref('')
const viewAttachmentData = ref([])
const viewAttachmentModalClick = async ({id}) => {
    viewAttachmentId.value=id
    viewAttachmentLoading.value = true
    const { error, code, data } = await dataApi.ancillaryDocumentsList({id: id})
    //处理数据
    viewAttachmentLoading.value = false
    if (!error && code === 200) {
        viewAttachmentData.value = getArrValue(data)
        if ( viewAttachmentData.value.length<1) {
             window.$message?.warning('该条记录不存在附件')
        }else{
             viewAttachmentModal.value = true
             viewCurFile( viewAttachmentData.value[0])
        }
       
    } else {
        viewAttachmentData.value = []
         
    }
}
const refeshAttachmentModalClick = async (id) => {
    const { error, code, data } = await dataApi.ancillaryDocumentsList({id: id})
    //处理数据
    viewAttachmentLoading.value = false
    if (!error && code === 200) {
        viewAttachmentData.value = getArrValue(data)
        if ( viewAttachmentData.value.length<1) {
             window.$message?.warning('该条记录不存在附件')
        }else{
             viewCurFile( viewAttachmentData.value[0])
        }
       
    } else {
        viewAttachmentData.value = []
         
    }
}
const attachmentPdfUrl = ref('')
const curFileData =ref ({})
//类型tab数据和相关处理
const tabTypeKey = ref('productionCertificate')
const tabTypeTab = ref([
    {key:'productionCertificate',  name: '生产合格证'},
    {key:'qualityInspectionReport', name: '厂家质检报告'},
    {key:'otherAccessories', name: '其他文件'},
]);
const tabTypeChange = (item) => {
    tabTypeKey.value = item?.key
    viewCurFile(curFileData.value)
    refeshAttachmentModalClick(viewAttachmentId.value)
}

//关闭查看附件
const viewAttachmentModalClose = () => {
    viewAttachmentModal.value = false
     curFileData.value=''
     attachmentPdfUrl.value=''
}
const uploadData = ref({})
const fileListData=ref([])
const listuploadref=ref('1')
//查看当前文件pdf
const viewCurFile = (item) => {
    curFileData.value=item
    viewAttachmentData.value.forEach((ele)=>{
        if (ele.name===item.name) {
            ele.isCheck=true
        }else{
            ele.isCheck=false
        }
    })
    if(tabTypeKey.value=='productionCertificate'&&item.productionCertificate.length>0){
        let arr=[]
        arr.push({name:item.productionCertificateName,url:item.productionCertificate})
        fileListData.value =getArrValue(arr)
        listuploadref.value='1'
    }else if(tabTypeKey.value=='qualityInspectionReport'&&item.qualityInspectionReport.length>0){
         let arr=[]
         arr.push({name:item.qualityInspectionReportName,url:item.qualityInspectionReport})
         fileListData.value =getArrValue(arr)
         listuploadref.value='2'
    }else if(tabTypeKey.value=='otherAccessories'&&item.otherAccessories.length>0){
          let arr=[]
        arr.push({name:item.otherAccessoriesName,url:item.otherAccessories})
         fileListData.value =getArrValue(arr)
         listuploadref.value='3'
    }else{
         attachmentPdfUrl.value=''
    }      
}

//上传进度
const uploadprogress = (res) => {
 console.log('进度');
}

const productionCertificatefile=ref('')
const qualityInspectionReportfile=ref('')
const otherAccessoriesfile=ref('')
//上传完成
const uploadFinished = async(res) => {
    if(tabTypeKey.value=='productionCertificate'){
        productionCertificatefile.value =res
    } else if (tabTypeKey.value=='qualityInspectionReport') {
        qualityInspectionReportfile.value=res
    }else{
        otherAccessoriesfile.value=res
    }
 
    const { error, code, data } = await dataApi.updateAncillaryDocument(
        {
            id:curFileData.value.id,
            productionCertificate:productionCertificatefile.value.link,
            qualityInspectionReport:qualityInspectionReportfile.value.link,
            otherAccessories:otherAccessoriesfile.value.link
        })
}

//样品信息数据
const samplingTableColumn = ref([
    {key:'materialName', name: '样品名称'},
    {key:'samplingDate', name: '取样时间'},
    {key:'specificationNumber', name: '样品编号'},
    {key:'specificationModel', name: '规格型号'},
    {key:'materialCount', name: '试样数量'},
    {key:'calculationUnit', name: '计算单位'},
    {key:'proposedPosition', name: '拟用部位'},
    {key:'representativeCount', name: '代表数量'},
    {key:'userName', name: '取样人'},
])
const samplingTableData = ref([])
const samplingTableLoading = ref(false)

//取样记录
const samplingRecordModal = ref(false)
const samplingRecordModalClick = async ({id}) => {
    samplingRecordModal.value = true
    samplingTableLoading.value = true
    const { error, code, data } = await dataApi.getSampleList({
        id: id
    })
    //处理数据
    samplingTableLoading.value = false
    if (!error && code === 200) {
        samplingTableData.value = getArrValue(data)
    } else {
        samplingTableData.value = []
    }
}

//关闭样品信息
const samplingRecordModalClose = () => {
    samplingRecordModal.value = false
    samplingTableData.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 "../../../styles/tentative/detect/test.scss";

.hc-switch-tab-content {
    .pdf-file-list-box {
        position: relative;
        border-right: 1px solid #e9e9e9;
        padding: 5px 0;
        overflow-y: auto;
        height: 100%;
        flex: 1;
       
        .file-item {
            position: relative;
            cursor: pointer;
            padding: 6px 10px;
            &:hover {
                color: var(--el-color-primary);
                background-color: var(--el-color-primary-light-8);
            }
            &.cur {
                color: var(--el-color-primary);
                background-color: var(--el-color-primary-light-8);
            }
        }
    }
    .hc-no-table-form {
        flex: 1;
    }
}

</style>
