<template>
    <hc-body split class="hc-tentative-collect-test-body">
        <template #left>
            <hc-card scrollbar>
                <template #header>
                    <div class="text-18px">汇总分类</div>
                </template>
                <div
                    v-for="(item) in testOpt" :key="item.id" class="mb-4"
                    :class="item.id === curItem?.id ? 'bg-slate-200' : ''" @click="handleItem(item)"
                >
                    <i class="ri-circle-fill" />
                    {{ item.className }}
                </div>
            </hc-card>
        </template>
        <hc-card>
            <template #header>
                <div class="w-50">
                    <el-select v-model="searchForm.contractId" placeholder="请选择" @change="changeContract">
                        <el-option
                            v-for="item in contractOptions" :key="item.id" :label="item.contractName"
                            :value="item.id"
                        />
                    </el-select>
                </div>
                <div class="ml-2 w-40">
                    <el-select
                        v-model="searchForm.detectionType" clearable block placeholder="检测类别"
                        @change="changeType"
                    >
                        <el-option v-for="item in typeData" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div class="ml-2 w-40">
                    <el-select v-model="searchForm.key1" clearable block placeholder="单位类型">
                        <el-option label="无接口1" value="1" />
                        <el-option label="无接口2" value="2" />
                    </el-select>
                </div>
                <div class="ml-2 w-64">
                    <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
                </div>
            </template>
            <template #extra>
                <HcTooltip keys="tentative_collect_test_print">
                    <el-button hc-btn color="#567722" @click="addClick">
                        <HcIcon name="add" />
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_collect_test_download">
                    <el-button
                        hc-btn color="#A16222" :loading="downLoading" :disabled="tableCheckedKeys.length === 0"
                        @click="downClick"
                    >
                        <HcIcon name="download" />
                        <span>下载</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_collect_test_del">
                    <el-button hc-btn color="#e03997" :disabled="tableCheckedKeys.length === 0" @click="delModalClick">
                        <HcIcon name="delete-bin-2" />
                        <span>删除</span>
                    </el-button>
                </HcTooltip>
            </template>
            <HcTable
                ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                @selection-change="tableSelection"
            >
                <template #action="{ row }">
                    <el-link type="primary" @click="viewPdf(row)">查看</el-link>
                    <!-- <el-link type="primary" @click="relatedSearchClick(row)">查阅关联</el-link> -->
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-card>

        <!-- 新增/编辑 -->
        <hc-new-dialog
            v-model="addFormShow" :loading="addFormLoading" title="新增分类" widths="30rem"
            @close="addModalClose" @save="addModalSave"
        >
            <el-form
                ref="addFormRef" :model="addFormModal" :rules="addFormRules" label-position="left"
                label-width="auto" size="large"
            >
                <el-form-item class="mb-0" label="合同段:" prop="contractId">
                    <el-select v-model="addFormModal.contractId" placeholder="请选择">
                        <el-option
                            v-for="item in contractOptions" :key="item.id" :label="item.contractName"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item class="mb-0 mt-4" label="汇总类别:" prop="classId">
                    <el-select v-model="addFormModal.classId" placeholder="请选择">
                        <el-option v-for="item in testOpt" :key="item.id" :label="item.className" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item class="mb-0 mt-4" label="报告时间:">
                    <HcDatePicker :dates="addbetweenTime" clearable @change="addbetweenTimeUpdate" />
                </el-form-item>
            </el-form>
            <el-form-item class="mb-0 mt-4" label="单位类型:" prop="unitType	">
                <el-select v-model="addFormModal.unitType	" placeholder="请选择">
                    <el-option v-for="item in unitOpt" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item class="mb-0 mt-4" label="检测类型:" prop="detectionType">
                <el-select v-model="addFormModal.detectionType" placeholder="请选择">
                    <el-option v-for="item in typeData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
        </hc-new-dialog>

        <!-- 查阅关联 -->
        <hc-dialog
            v-model="isRelatedSearch" :footer="false" is-table title="查阅关联" widths="80%" :padding="false"
            @close="relatedSearchModalClose"
        >
            <div class="hc-related-search-box relative mt-10px">
                <hc-card-item title="样品信息">
                    <hc-table :column="relatedColumn1" :datas="relatedData1" :is-index="false" />
                </hc-card-item>
                <hc-card-item title="委托单信息" class="mt-14px">
                    <hc-table :column="relatedColumn2" :datas="relatedData2" :is-index="false">
                        <template #status="{ row }">
                            <el-tag v-if="row.status === 1" type="info" effect="dark">未上报</el-tag>
                            <el-tag v-if="row.status === 2" type="warning" effect="dark">已上报-待审批</el-tag>
                            <el-tag v-if="row.status === 3" type="primary" effect="dark">待试验</el-tag>
                            <el-tag v-if="row.status === 4" type="success" effect="dark">委托完成</el-tag>
                        </template>
                    </hc-table>
                </hc-card-item>
                <hc-card-item title="设备采集信息" class="mt-14px">
                    <hc-table :column="relatedColumn3" :datas="relatedData3" :is-index="false" />
                </hc-card-item>
            </div>
        </hc-dialog>
    </hc-body>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { arrToId, getArrValue, getObjVal, isNullES, isString } from 'js-fast-way'
import { HcDelMsg } from 'hc-vue3-ui'
import { getDictionary } from '~api/other'
import { toPdfPage } from '~uti/btn-auth'
import dataApi from '~api/tentative/detect/test'
import testSampleApi from '~api/tentative/material/testSample'
import commissionApi from '~api/tentative/detect/commission'
import acquisitionApi from '~api/tentative/acquisition/data'
import { download, getContractList, getPage, getSummaryList, removeByIds, save } from '~api/tentative/collect/test'

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)

const isCollapse = ref(useAppState.getCollapse)

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

//渲染完成
onMounted(async () => {
    await gettypeData()
    await getContractOpt()
    await getTextOpt()
    getTableData()
})

//搜索表单
const searchForm = ref({
    contractId: null, detectionType: null, betweenTime: null,
    current: 1, size: 20, total: 0,
})

//获取合同段列表
const getContractOpt = async () => {
    const { data } = await getContractList({
        contractId: contractId.value,
        projectId: projectId.value,
    })
    const res = getArrValue(data)
    contractOptions.value = res
    if (res.length <= 0) return
    let cid
    for (let i = 0; i < res.length; i++) {
        if (contractId.value == res[i].id) {
            cid = res[i].id
        }
    }
    searchForm.value.contractId = isNullES(cid) ? res[0].id : cid
}

//获取汇总分类列表
const testOpt = ref([])
const getTextOpt = async () => {
    const { error, code, data } = await getSummaryList()
    //判断状态
    if (!error && code === 200) {
        let resdata = getArrValue(data)
        testOpt.value = resdata
        if (testOpt.value.length > 0) {
            curItem.value = testOpt.value[0]
        }

    } else {
        testOpt.value = []
    }
}
const curItem = ref(null)
const handleItem = (item) => {
    curItem.value = item
    getTableData()
}
//检测类别
const typeData = ref([])
//获取检测类别

const gettypeData = async () => {
    const { data } = await getDictionary({
        code: 'trial_detection_category',
    })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            value: Number(newData[i]['dictKey']),
        })
    }
    typeData.value = newArr
}


//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr, query }) => {
    betweenTime.value = arr
    searchForm.value.startDate = arr[0]
    searchForm.value.endDate = arr[1]
    getTableData()
}
const addbetweenTime = ref(null)
const addbetweenTimeUpdate = ({ arr, query }) => {
    addbetweenTime.value = arr
    addFormModal.value.startDate = arr[0]
    addFormModal.value.endDate = arr[1]

}

//选择检测类别
const changeType = () => {
    getTableData()
}
const changeContract = () => {
    getTableData()
}


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

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'summaryNumber', name: '汇总编号' },
    { key: 'classIdName', name: '汇总类别' },
    { key: 'detectionTypeName', name: '检测类型' },
    { key: 'summaryDateName', name: '汇总日期' },
    { key: 'no-key', name: '单位类型' },
    { key: 'action', name: '操作', width: 100 },
])

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    if (!searchForm.value.contractId) {
        window.$message.warning('请选择合同段')
        return
    }
    if (curItem.value) {
        const { error, code, data } = await getPage({
            ...searchForm.value,
            classId: curItem.value?.id,
        })
        //判断状态
        if (!error && code === 200) {
            tableData.value = getArrValue(data?.records)
            searchForm.value.total = data?.total ?? 0
        } else {
            tableData.value = []
            searchForm.value.total = 0
        }
    } else {
        window.$message.warning('请先选择汇总分类')
    }

}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//删除
const delModalClick = () => {
    if (tableCheckedKeys.value.length === 0) {
        window.$message.warning('请先选择数据')
        return
    }
    HcDelMsg(async (resolve) => {
        await removeContractTreeNode()
        resolve() //关闭弹窗的回调
    })
}
const removeContractTreeNode = async () => {
    const loadingInstance = window.$loading.service({
        fullscreen: true,
        text: '删除节点中，请耐心等待...',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    const { error, code, msg } = await removeByIds({
        ids: arrToId(tableCheckedKeys.value),
    })
    loadingInstance.close()
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message.error(msg)
    }
}
//左右拖动，改变树形结构宽度
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
    }
}
//查看pdf
const viewPdf = (row) => {
    const { pdfUrl } = row
    if (pdfUrl) {
        toPdfPage(pdfUrl)
    } else {
        window.$message.warning('暂无数据')
    }
}

//新增试验汇总
const addFormModal = ref({})
const addFormShow = ref(false)
const addFormLoading = ref(false)
const addClick = () => {

    addFormShow.value = true

}
const addModalClose = () => {
    addFormShow.value = false
    addFormModal.value = {}

}

const addFormRules = ref(null)
const addFormRef = ref(null)

const addModalSave = async () => {
    console.log(addFormModal.value)
    addFormLoading.value = true
    const { error, code, msg } = await save({
        ...addFormModal.value,

    })
    addFormLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window.$message.success(msg)
        addFormShow.value = false
        getTableData()

    }
}
const unitOpt = ref([
    { name: '施工', id: '1' },
])
const downLoading = ref(false)
const downClick = async () => {
    downLoading.value = true
    const { error, code, data } = await download({
        ids: arrToId(tableCheckedKeys.value),
    })
    downLoading.value = false

    const res = isString(data) ? data || '' : ''
    if (!error && code === 200 && res) {
        window.open(res, '_blank')
    }
}

//关联查阅
const isRelatedSearch = ref(false)
const relatedSearchClick = (row) => {
    isRelatedSearch.value = true
    //获取样品信息
    getSampleList(row.id)
    //获取委托单
    getCommissionData(row.entrustId)
    //获取关联设备
    getAcquisitionData(row.loadDataId)
}

//样品信息
const relatedColumn1 = [
    { 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: '取样人' },
    { key: 'carryTime', name: '入库时间', align: 'center' },
    { key: 'createTime', name: '试验时间', align: 'center' },
    { key: 'no-key', name: '样品处理' },
    { key: 'no-key', name: '时间(或处理原因)' },
]
const relatedData1 = ref([])
const getSampleList = async (id) => {
    relatedData1.value = []
    if (isNullES(id) || id == 0) return
    const { data } = await dataApi.getSampleList({ id })
    relatedData1.value = getArrValue(data)
}

//委托单信息
const relatedColumn2 = [
    { key: 'entrustInfo', name: '委托单位' },
    { key: 'entrustNo', name: '委托单编号' },
    { key: 'entrustName', name: '委托单名称' },
    { key: 'status', name: '委托单状态', width: 120, align: 'center' },
]
const relatedData2 = ref([])
const getCommissionData = async (id) => {
    relatedData2.value = []
    if (isNullES(id) || id == 0) return
    const { data } = await commissionApi.detail(id)
    const res = getObjVal(data)
    relatedData2.value = res ? [res] : []
}

//设备采集信息
const relatedColumn3 = [
    { key: 'engineInfo', name: '工程部位' },
    { key: 'deviceName', name: '设备名称' },
    { key: 'equipmentAcquisitionNumber', name: '设备采集编号', width: 180, align: 'center' },
    { key: 'testDate', name: '试验日期', width: 160, align: 'center' },
    { key: 'specificationNumber', name: '样品编号', width: 180, align: 'center' },
    { key: 'testTypeName', name: '试验类型', width: 100, align: 'center' },
    { key: 'beArea', name: '承压面积(mm2)', width: 100, align: 'center' },
    { key: 'specimenSize', name: '试件尺寸(mm)', width: 100, align: 'center' },
    { key: 'desStrength', name: '设计强度(MPa)', width: 100, align: 'center' },
    { key: 'no-key', name: '龄期(d)', width: 100, align: 'center' },
    { key: 'load1', name: '荷载1(KN)', width: 100, align: 'center' },
    { key: 'load2', name: '荷载2(KN)', width: 100, align: 'center' },
    { key: 'load3', name: '荷载3(KN)', width: 100, align: 'center' },
    { key: 'no-key', name: '荷载4(KN)', width: 100, align: 'center' },
    { key: 'no-key', name: '荷载5(KN)', width: 100, align: 'center' },
    { key: 'no-key', name: '荷载6(KN)', width: 100, align: 'center' },
    { key: 'no-key', name: '强度代表值(MPa)', width: 100, align: 'center' },
    {
        name: '最大力总延伸(%)',
        children: [
            { key: 'maxConceal1', name: '1', width: 100, align: 'center' },
            { key: 'maxConceal2', name: '2', width: 100, align: 'center' },
            { key: 'maxConceal3', name: '3', width: 100, align: 'center' },
        ],
    },
    //{ key: 'dataQualified', name: '试验结果是否合格', width: 100, align: 'center' },
    { key: 'dataStatus', name: '数据状态', width: 100, align: 'center' },
]
const relatedData3 = ref([])
const getAcquisitionData = async (id) => {
    relatedData3.value = []
    if (isNullES(id) || id == 0) return
    const { data } = await acquisitionApi.selectDataInfoById(id)
    const res = getObjVal(data)
    if (res) {
        relatedData3.value = res ? [res] : []
        setRelatedColumn3(res.testTypePId)
    }
}

//设置表头
const setRelatedColumn3 = (type) => {
    //压力机
    if (type === '1') {
        relatedColumn3.value = [
            { key: 'engineInfo', name: '工程部位' },
            { key: 'deviceName', name: '设备名称' },
            { key: 'equipmentAcquisitionNumber', name: '设备采集编号', width: 180, align: 'center' },
            { key: 'testDate', name: '试验日期', width: 160, align: 'center' },
            { key: 'specificationNumber', name: '样品编号', width: 180, align: 'center' },
            { key: 'testTypeName', name: '试验类型', width: 100, align: 'center' },
            { key: 'beArea', name: '承压面积(mm2)', width: 100, align: 'center' },
            { key: 'specimenSize', name: '试件尺寸(mm)', width: 100, align: 'center' },
            { key: 'desStrength', name: '设计强度(MPa)', width: 100, align: 'center' },
            { key: 'ageDate', name: '龄期(d)', width: 100, align: 'center' },
            { key: 'load1', name: '荷载1(KN)', width: 100, align: 'center' },
            { key: 'load2', name: '荷载2(KN)', width: 100, align: 'center' },
            { key: 'load3', name: '荷载3(KN)', width: 100, align: 'center' },
            { key: 'no-key', name: '荷载4(KN)', width: 100, align: 'center' },
            { key: 'no-key', name: '荷载5(KN)', width: 100, align: 'center' },
            { key: 'no-key', name: '荷载6(KN)', width: 100, align: 'center' },
            { key: 'strengthAVG', name: '强度代表值(MPa)', width: 100, align: 'center' },
            {
                name: '最大力总延伸(%)',
                children: [
                    { key: 'maxConceal1', name: '1', width: 100, align: 'center' },
                    { key: 'maxConceal2', name: '2', width: 100, align: 'center' },
                    { key: 'maxConceal3', name: '3', width: 100, align: 'center' },
                ],
            },
            //{ key: 'dataQualified', name: '试验结果是否合格', width: 100, align: 'center' },
            { key: 'dataStatus', name: '数据状态', width: 100, align: 'center' },
        ]
    } else if (type === '2') {
        //万能机
        relatedColumn3.value = [
            { key: 'engineInfo', name: '工程部位' },
            { key: 'deviceName', name: '设备名称' },
            { key: 'equipmentAcquisitionNumber', name: '设备采集编号', width: 180, align: 'center' },
            { key: 'testDate', name: '试验日期', width: 160, align: 'center' },
            { key: 'specificationNumber', name: '样品编号', width: 180, align: 'center' },
            { key: 'testTypeName', name: '试验类型', width: 100, align: 'center' },
            { key: 'no-key', name: '牌号', width: 100, align: 'center' },
            { key: 'no-key', name: '公称直径(mm)', width: 100, align: 'center' },
            { key: 'no-key', name: '规格', width: 100, align: 'center' },
            {
                name: '最大力/荷载(KN)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            {
                name: '抗拉强度/强度代表值(MPa)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            {
                name: '上屈服力(KN)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            {
                name: '下屈服力(KN)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            {
                name: '上屈服强度(MPa)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            {
                name: '下屈服强度(MPa)',
                children: [
                    { key: 'no-key', name: '1', width: 100, align: 'center' },
                    { key: 'no-key', name: '2', width: 100, align: 'center' },
                    { key: 'no-key', name: '3', width: 100, align: 'center' },
                    { key: 'no-key', name: '4', width: 100, align: 'center' },
                    { key: 'no-key', name: '5', width: 100, align: 'center' },
                    { key: 'no-key', name: '6', width: 100, align: 'center' },
                ],
            },
            { key: 'dataStatus', name: '数据状态', width: 100, align: 'center' },
        ]
    }
}

//关闭关联查阅
const relatedSearchModalClose = () => {
    isRelatedSearch.value = false
    relatedData1.value = []
    relatedData2.value = []
    relatedData3.value = []
}
</script>

<style lang="scss" scoped>
.title_box {
    font-size: 24px;
    font-weight: bolder;
}
</style>
