<template>
    <hc-card-item class="hc-test-sample-card-item">
        <template #header>
            <div class="w-200px">
                <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 w-250px">
                <hc-search-input v-model="searchForm.materialName" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button type="danger" :disabled="tableCheckedKeys.length <= 0" @click="batchCancel">取消待测</el-button>
        </template>
        <hc-table
            :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
            :index-style="{ width: 60 }" :check-style="{ width: 29 }" @selection-change="tableSelection"
        >
            <template #action="{ row }">
                <el-link type="primary" @click="rowReports(row)">创建报告</el-link>
                <el-link type="danger" @click="rowCancel(row)">取消待测</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 创建报告 -->
        <hc-new-dialog v-model="rowActionModal" is-footer-center title="创建报告" widths="40rem" @close="rowActionModalClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="委托单位：">
                            <el-input v-model="formModel.entrustInfo" placeholder="委托单位" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="委托单位名称：">
                            <el-input v-model="formModel.entrustName" placeholder="委托单位名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取样名称：">
                            <el-input v-model="formModel.materialName" placeholder="取样名称" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="取样数量：">
                            <el-input v-model="formModel.materialCount" placeholder="取样数量" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="样品编号：">
                            <el-input v-model="formModel.entrustNo" placeholder="样品编号" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="试验数量：" prop="expCount">
                            <el-input v-model="formModel.expCount" placeholder="试验数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规格型号：">
                            <el-input v-model="formModel.specificationModel" placeholder="规格型号" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="计算单位：">
                            <el-input v-model="formModel.calculationUnit" placeholder="计算单位" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="rowActionModalClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="saveLoading" @click="rowActionSave">创建</el-button>
            </template>
        </hc-new-dialog>
    </hc-card-item>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import router from '~src/router/index'
import { getErtractInfo } from '~api/other'
import { HcDelMsg } from 'hc-vue3-ui'
import { arrToId, formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/tentative/material/testSample'
import { setStoreValue } from '~uti/storage'

//参数
const props = defineProps({
    tree: {
        type: Object,
        default: () => ({}),
    },
})

//变量
const store = useAppStore()
const projectId = ref(store.getProjectId)
const contractId = ref(store.getContractId)
const contractInfo = ref(store.getContractInfo)

//渲染完成
onMounted(() => {
    getContractData()
})

//监听数据
const treeInfo = ref(props.tree)
watch(() => props.tree, (obj) => {
    treeInfo.value = getObjValue(obj)
    searchClick()
})

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

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

//搜索
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: 'specificationModel', name: '规格型号', align: 'center' },
    { key: 'materialCount', name: '试样数量', align: 'center' },
    { key: 'calculationUnit', name: '计算单位', align: 'center' },
    { key: 'proposedPosition', name: '拟用部位' },
    { key: 'representativeCount', name: '代表数量', align: 'center' },
    { key: 'userName', name: '取样人', align: 'center' },
    { key: 'no-key', name: '待测时间', align: 'center' },
    { key: 'action', name: '操作', width: 150, align: 'center' },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    const { primaryKeyId } = treeInfo.value
    if (isNullES(primaryKeyId)) return
    tableLoading.value = true
    const { error, code, data } = await mainApi.queryPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
        nodeId: primaryKeyId || '',
    })
    //处理数据
    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 formRef = ref(null)
const formModel = ref({})
const formRules = {
    expCount: {
        required: true,
        trigger: 'blur',
        message: '请填写试验数量',
    },
}

//弹窗
const rowActionModal = ref(false)

//创建报告
const rowReports = (row) => {
    formModel.value = row
    rowActionModal.value = true
}

//提交保存
const saveLoading = ref(false)
const rowActionSave = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return
    saveLoading.value = true
    const { id, expCount } = formModel.value
    let form = { id, expCount, sampleStatus: 4 }
    const { error, code, msg } = await mainApi.update(form)
    saveLoading.value = false
    if (!error && code === 200) {
        window.$message.success('创建成功')
        rowActionModalClose()
        getTableData().then()
        //跳转到试验填报的新增
        setStoreValue('testTreeItem', treeInfo.value)
        setStoreValue('prenodeDataInfo', treeInfo.value)
        const { contractType } = contractInfo.value
        const { primaryKeyId } = treeInfo.value
        router.push({
            path: '/tentative/detect/test-form',
            query: {
                nodeId: primaryKeyId || '',
                dataType: contractType > 0 ? contractType + '' : '1',
                commissionId: id,
                isaddType: true,
            },
        }).then()
    } else {
        window.$message.error(msg || '创建失败')
    }
}

//关闭弹窗
const rowActionModalClose = () => {
    rowActionModal.value = false
    formModel.value = {}
}

//取消待测
const rowCancel = (row) => {
    HcDelMsg({
        title: '确认取消提醒',
        text: '请谨慎考虑后，确认是否取消待测？',
    }, async (resolve) => {
        await tableDataCancel(row.id)
        resolve() //关闭弹窗的回调
    })
}

//批量取消待测
const batchCancel = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选需要取消的数据')
        return
    }
    HcDelMsg({
        title: '确认取消提醒',
        text: '请谨慎考虑后，确认是否取消待测？',
    }, async (resolve) => {
        await tableDataCancel(arrToId(rows))
        resolve() //关闭弹窗的回调
    })
}

//取消待测
const tableDataCancel = async (ids) => {
    let form = { id: ids, sampleStatus: 2 }
    const { error, code, msg } = await mainApi.update(form)
    if (!error && code === 200) {
        window.$message.success('取消成功')
        getTableData().then()
    } else {
        window.$message.error(msg || '创建失败')
    }
}
</script>
