<template>
    <!-- 关联取样材料 -->
    <hc-new-dialog v-model="isShow" is-footer-center is-table title="关联取样材料" widths="80%" @close="linkSamplingClose">
        <hc-body v-if="isShow" split>
            <template #left>
                <hc-new-card scrollbar>
                    <TestTree
                        :auto-expand-keys="treeAutoExpandKeys" :project-id="projectId" :tenant-id="userInfo?.tenant_id"
                        :wbs-temp-id="projectInfo?.referenceWbsTemplateIdTrial" :wbs-type="2" @node-tap="wbsElTreeClick"
                    />
                </hc-new-card>
            </template>
            <hc-new-card>
                <template #header>
                    <div class="w-50">
                        <el-select v-model="searchForm.contractId" placeholder="选择合同段" filterable block>
                            <el-option v-for="item in contractData" :key="item.id" :label="item.contractName" :value="item.id" />
                        </el-select>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <hc-icon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :index-style="{ width: 60 }">
                    <template #action="{ row }">
                        <el-link v-if="row.id == currentId" type="success" @click="rowCancel(row)">取消选择</el-link>
                        <el-link v-else type="primary" @click="rowSelect(row)">选择</el-link>
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template>
            </hc-new-card>
        </hc-body>
        <template #footer>
            <el-button @click="linkSamplingClose">取消</el-button>
            <el-button hc-btn type="primary" @click="linkSamplingClick">确定</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import TestTree from '~src/views/tentative/material/components/TestTree.vue'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import samplingApi from '~api/tentative/material/sampling'
import { getArrValue } from 'js-fast-way'

//变量
const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)

const isShow = defineModel('modelValue', {
    default: false,
})

//深度监听数据
const curId = defineModel('id', {
    type: [String, Number],
    default: '',
})

//监听
watch(() => curId.value, (id) => {
    currentId.value = id
})

//监听
watch(() => isShow.value, (show) => {
    if (show) getContractData()
})

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

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

//获取合同段信息
const contractData = ref([])
const getContractData = async () => {
    const { data } = await samplingApi.getErtractInfo({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const res = getArrValue(data)
    contractData.value = res
    if (res.length > 0) {
        searchForm.value.contractId = res[0].id
    }
}

//树被点击
const nodeDataInfo = ref({})
const wbsElTreeClick = ({ data, keys }) => {
    nodeDataInfo.value = data
    //缓存自动展开
    treeAutoExpandKeys.value = keys
    setStoreValue('testTreeExpandKeys', keys)
    //改变搜索表单数据
    searchForm.value.nodeId = data['primaryKeyId'] || ''
    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 tableColumn = ref([
    { key: 'materialName', name: '取样名称' },
    { key: 'samplingDate', name: '取样日期', width: 100, align: 'center' },
    { key: 'specificationNumber', name: '样品编号' },
    { key: 'specificationModel', name: '规格型号', width: 80, align: 'center' },
    { key: 'materialCount', name: '试样数量', width: 80, align: 'center' },
    { key: 'calculationUnit', name: '计算单位', width: 80, align: 'center' },
    { key: 'proposedPosition', name: '拟用部位', width: 80, align: 'center' },
    { key: 'representativeCount', name: '代表数量', width: 80, align: 'center' },
    { key: 'userName', name: '取样人', width: 80, align: 'center' },
    { key: 'action', name: '操作', width: 80, align: 'center', fixed: 'right' },
])

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await samplingApi.queryPage({
        projectId: projectId.value,
        ...searchForm.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 currentId = ref(null)
const rowSelect = (row) => {
    currentId.value = row.id
}

//取消选择
const rowCancel = () => {
    currentId.value = null
}

//确认关联取样材料
const linkSamplingClick = () => {
    curId.value = currentId.value
    linkSamplingClose()
}

//取消关联取样材料
const linkSamplingClose = () => {
    isShow.value = false
}
</script>
