<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-date-picker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
            </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="batchDel">删除</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 #entrustStatus="{ row }">
                <!-- 未上报 -->
                <el-button v-if="row.entrustStatus === 1" type="info" size="small">{{ row.entrustStatusName || '-' }}</el-button>
                <!-- 待审批 -->
                <el-button v-if="row.entrustStatus === 2" type="info" size="small">{{ row.entrustStatusName || '-' }}</el-button>
                <!-- 待试验 -->
                <el-button v-if="row.entrustStatus === 3" type="primary" size="small">{{ row.entrustStatusName || '-' }}</el-button>
                <!-- 已通过 -->
                <el-button v-if="row.entrustStatus === 4" type="success" size="small">{{ row.entrustStatusName || '-' }}</el-button>
                <!-- 已废除 -->
                <el-button v-if="row.entrustStatus === 5" type="danger" size="small">{{ row.entrustStatusName || '-' }}</el-button>
            </template>
            <template #action="{ row }">
                <el-link v-if="row.entrustStatus === 4" type="primary" @click="rowDispose(row)">样品处理</el-link>
                <el-link v-else type="primary" :disabled="!(row.entrustStatus === 1 || row.entrustStatus === 5)" @click="fillReportClick(row)">填写报告</el-link>
                <el-link type="danger" :disabled="row.entrustStatus === 2" @click="rowDel(row)">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 样品处理 -->
        <hc-new-dialog v-model="disposeModal" is-footer-center title="样品处理" widths="40rem" @close="disposeClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="left" label-width="auto">
                <el-form-item label="处理方式：" prop="repealType">
                    <el-radio-group v-model="formModel.repealType">
                        <el-radio :value="1">处理</el-radio>
                        <el-radio :value="2">留样</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="formModel.repealType === 1" label="处理原因：" prop="repealReason">
                    <el-input v-model="formModel.repealReason" type="textarea" :rows="5" resize="none" />
                </el-form-item>
                <el-form-item v-if="formModel.repealType === 2" label="留样时间：" prop="resamStartTime">
                    <hc-date-picker :dates="formTime" clearable @change="formTimeUpdate" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="disposeClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="saveLoading" @click="disposeSave">确定</el-button>
            </template>
        </hc-new-dialog>
    </hc-card-item>
</template>

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

//参数
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: 4, startTime: null, endTime: null, 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 betweenTime = ref(null)
const betweenTimeUpdate = ({ arr }) => {
    betweenTime.value = arr
    if (arr.length > 0) {
        searchForm.value.startTime = arr[0]
        searchForm.value.endTime = arr[1]
    } else {
        searchForm.value.startTime = null
        searchForm.value.endTime = null
    }
}

//搜索
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: 'expCount', name: '试验数量', align: 'center' },
    { key: 'key5', name: '剩余数量', align: 'center' },
    { key: 'calculationUnit', name: '计算单位', align: 'center' },
    { key: 'proposedPosition', name: '拟用部位' },
    { key: 'representativeCount', name: '代表数量', align: 'center' },
    { key: 'userName', name: '取样人', align: 'center' },
    { key: 'userName', name: '取样人', align: 'center' },
    { key: 'createTime', name: '创建试验时间', align: 'center' },
    { key: 'entrustStatus', name: '报告状态', align: 'center' },
    { key: 'action', name: '操作', width: 120, 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 = {
    repealType: {
        required: true,
        trigger: 'blur',
        message: '请选择处理方式',
    },
    repealReason: {
        required: true,
        trigger: 'blur',
        message: '请填写处理原因',
    },
    resamStartTime: {
        required: true,
        trigger: 'blur',
        message: '请选择留样时间',
    },
}

//样品处理
const disposeModal = ref(false)
const rowDispose = (row) => {
    formModel.value = {
        id: row.id,
        repealType: 1,
    }
    disposeModal.value = true
}

//日期时间被选择
const formTime = ref(null)
const formTimeUpdate = ({ arr }) => {
    formTime.value = arr
    if (arr.length > 0) {
        formModel.value.resamStartTime = arr[0]
        formModel.value.resamEndTime = arr[1]
    } else {
        formModel.value.resamStartTime = ''
        formModel.value.resamEndTime = ''
    }
}

//确定提交
const saveLoading = ref(false)
const disposeSave = async () => {
    const isForm = await formValidate(formRef.value)
    if (!isForm) return
    const { error, code, msg } = await mainApi.update(formModel.value)
    saveLoading.value = false
    if (!error && code === 200) {
        window.$message.success('提交成功')
        disposeClose()
        getTableData().then()
    } else {
        window.$message.error(msg || '操作失败')
    }
}

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

//删除
const rowDel = (row) => {
    HcDelMsg(async (resolve) => {
        await sampleRemoveApi(row.id)
        resolve()
    })
}

//批量删除
const batchDel = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要删除的数据')
        return
    }
    HcDelMsg(async (resolve) => {
        await sampleRemoveApi(arrToId(rows))
        resolve()
    })
}

//删除
const sampleRemoveApi = async (ids) => {
    const { error, code, msg } = await mainApi.sampleRemove(ids)
    if (!error && code === 200) {
        window.$message.success('删除成功')
        getTableData().then()
    } else {
        window.$message.error(msg ?? '删除失败')
    }
}

//填写报告
const fillReportClick = (row) => {
    const { contractType } = contractInfo.value
    const { primaryKeyId } = treeInfo.value
    router.push({
        path: '/tentative/detect/test-form',
        query: {
            nodeId: primaryKeyId || '',
            dataType: contractType > 0 ? contractType + '' : '1',
            commissionId: row.id,
            isaddType: true,
        },
    })
}
</script>
