<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-tabs type="border-card">
                <el-tab-pane label="原矿试验数据管理表">
                    <el-form :inline="true">
                        <el-row gutter="1">
                            <el-col span="5">
                                <el-form-item label="试验日期" style="margin-bottom: 0px;">
                                    <el-date-picker v-model="query.testDate" type="daterange" align="right"
                                        unlink-panels range-separator="至" start-placeholder="开始时间"
                                        end-placeholder="结束时间" :picker-options="pickerOptions" style="width: 200px;"
                                        value-format="YYYY-MM-DD" format="YYYY-MM-DD">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col span="5">
                                <el-form-item label="矿石名称" style="margin-bottom: 5px;" prop="matlNm">
                                    <el-select v-model="query.matlNm" filterable placeholder="请选择矿石名称"
                                        style="width: 200px" clearable>
                                        <el-option v-for="item in matlNmList" :key="item.matlNm" :label="item.matlNm"
                                            :value="item.matlNm" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col span="5">
                                <el-form-item label="试验类型" style="margin-bottom: 5px;" prop="testTy">
                                    <el-input v-model="query.testTy" placeholder="请输入试验类型" clearable
                                        style="width: 200px;"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-row style="margin-top: 5px;">
                        <el-button type="primary" plain @click="handleSearch">查询</el-button>
                        <el-button type="success" plain @click="handleAdd">新增</el-button>
                        <!-- <el-button type="danger" plain @click="handleRemoveBatch">删除</el-button> -->
                    </el-row>
                    <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                        style="margin-top: 5px;" @row-dblclick="handleRowDblClick" ref="tableRef">
                        <el-table-column type="selection" fixed></el-table-column>
                        <el-table-column type="index" label="序号" align="center" width="60">
                            <template #default="scope">
                                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="testDate" label="试验日期" width="240" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="matlNm" label="矿石名称" width="240" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="testTy" label="试验类型" width="240" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="docNm" label="文档名称" width="240" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
                            <template #default="scope">
                                <el-button type="info" plain @click="editFile(scope.row)">编辑附件</el-button>
                                <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes"
                        :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 5px;">
                    </el-pagination>

                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-tabs type="border-card">
                <!-- <el-tab-pane label="原矿品位">
                    <OreTestRaw :tabsValue="multipleSelection"></OreTestRaw>
                </el-tab-pane> -->
                <el-tab-pane label="不选矿原矿试验结果">
                    <OreTestNbe :tabsValue="multipleSelection"></OreTestNbe>
                </el-tab-pane>
                <!-- <el-tab-pane label="浮选-磁选试验结果">
                    <OreTestFmbeRslt1 :tabsValue="multipleSelection"></OreTestFmbeRslt1>
                </el-tab-pane> -->
                <el-tab-pane label="浮选-磁选多元素化验结果">
                    <OreTestFmbeRslt2 :tabsValue="multipleSelection"></OreTestFmbeRslt2>
                </el-tab-pane>
                <!-- <el-tab-pane label="磁选试验结果">
                    <OreTestMbeRslt1 :tabsValue="multipleSelection"></OreTestMbeRslt1>
                </el-tab-pane> -->
                <el-tab-pane label="磁选多元素化验结果">
                    <OreTestMbeRslt2 :tabsValue="multipleSelection"></OreTestMbeRslt2>
                </el-tab-pane>
                <!-- <el-tab-pane label="浮选试验结果">
                    <OreTestFbeRslt1 :tabsValue="multipleSelection"></OreTestFbeRslt1>
                </el-tab-pane> -->
                <el-tab-pane label="浮选多元素化验结果">
                    <OreTestFbeRslt2 :tabsValue="multipleSelection"></OreTestFbeRslt2>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-dialog :close-on-click-modal="false" draggable :title="dialogName" v-model="dialogVisible" width="1200px"
            top="5vh" @open="openDialog">
            <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-form-item label="试验日期" prop="testDate">
                    <el-date-picker v-model="form.testDate" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD" placeholder="请选择试验日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="矿石名称" prop="matlNm">
                    <el-select v-model="form.matlNm" filterable placeholder="请选择矿石名称" style="width: 200px" clearable>
                        <el-option v-for="item in matlNmList" :key="item.matlNm" :label="item.matlNm"
                            :value="item.matlNm" clearable />
                    </el-select>
                </el-form-item>
                <el-form-item label="试验类型" prop="testTy">
                    <el-input v-model="form.testTy" clearable style="width: 200px" placeholder="请输入试验类型"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :close-on-click-modal="false" draggable v-model="dialogVisibleFile" width="1200px" @open="openDialog"
            @close="closeDialogFile">
            <el-card :body-style="cardBodyStyle">
                <Attachment ref="AttachmentRefManual" :fId="fId"></Attachment>
            </el-card>
        </el-dialog>

    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import OreTestRaw from '@/views/pla/OreTestMain/OreTestRaw.vue'
import OreTestNbe from '@/views/pla/OreTestMain/OreTestNbe.vue'
import OreTestFmbeRslt1 from '@/views/pla/OreTestMain/OreTestFmbeRslt1.vue'
import OreTestFmbeRslt2 from '@/views/pla/OreTestMain/OreTestFmbeRslt2.vue'
import OreTestMbeRslt1 from '@/views/pla/OreTestMain/OreTestMbeRslt1.vue'
import OreTestMbeRslt2 from '@/views/pla/OreTestMain/OreTestMbeRslt2.vue'
import OreTestFbeRslt1 from '@/views/pla/OreTestMain/OreTestFbeRslt1.vue'
import OreTestFbeRslt2 from '@/views/pla/OreTestMain/OreTestFbeRslt2.vue'

//文件上传
import Attachment from '@/components/Attachment.vue';
const fId = ref(null)
const AttachmentRefManual = ref(null)

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance,
    nextTick
} from 'vue'

import SearchBox from '@/components/SearchBox.vue'
const searchBarRef = ref(null)

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)


onMounted(() => {
    handleSearch()
    getmatlNmList()
})


// 外矿名称列表
const matlNmList = ref([])
const getmatlNmList = () => {
    var url = 'pla/PropMatl/query'
    var param = {
        page: 1,
        rows: 999999,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            matlNmList.value = response.data.data.records
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}


/**
 *   查询
 */


//双击表格某一行
const tableRef = ref(null);
// const handleRowDblClick = (row) => {
//     console.log(tableRef.value.selection)
//   // 勾选当前行
//   tableRef.value.toggleRowSelection(row, true);
// };

const handleRowDblClick = async (row) => {
    // 确保 tableRef 已经初始化
    if (tableRef.value) {
        // 使用 nextTick 确保 DOM 更新完成
        await nextTick();

        // 检查当前行是否已经被选中
        const isSelected = tableRef.value.selection?.includes(row) ?? false;

        // 切换选中状态
        tableRef.value.toggleRowSelection(row, !isSelected);

        if (isSelected) {
            ElMessage.info(`取消选中第 ${tableData.value.indexOf(row) + 1} 行`);
        } else {
            ElMessage.info(`选中第 ${tableData.value.indexOf(row) + 1} 行`);
        }
    } else {
        ElMessage.warning('表格尚未初始化');
    }
    // 这里可以添加双击行的具体逻辑
};


const query = ref({
    testDate: [proxy.$dayjs().subtract(1, 'month').format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')],
    matlNm: '',
    testTy: ''
})
const tableData = ref([])
const handleSearch = () => {
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'pla/OreTestMain/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
    testDate: '',
    matlNm: '',
    testTy: '',
    docNm: ''
})
const ruleFormRef = ref()
const rules = reactive({
    testDate: [{ required: true, message: '请选择试验日期', trigger: ['change', 'blur'] }],
    matlNm: [{ required: true, message: '请选择矿石名称', trigger: 'change' | 'blur' }],
    testTy: [{ max: 15, message: '试验类型超过有效长度', trigger: 'change' | 'blur' }]
})


const dialogName = ref('')
const handleAdd = () => {
    form.value = {
        testDate: '',
        matlNm: '',
        testTy: '',
        docNm: ''
    }
    dialogName.value = '新增'
    dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'pla/OreTestMain/save'
            var param = {
                json: JSON.stringify(form.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    form.value = response.data.data
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    getTableData()
                    dialogVisible.value = false
                } else {
                    // ElMessage.error('操作失败！' + response.data.msg)
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    dialogName.value = '编辑'
    dialogVisible.value = true
    form.value = row
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            var url = 'pla/OreTestMain/remove'
            var param = {
                id: row.id
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getTableData()
                } else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败' + response.data.msg
                    });
                }
            });
            proxy.$axios.get('framework/Common/queryFile', { fId: row.id }).then(response => {
                if (response.data.code == 0) {
                    tableDataFile.value = response.data.data
                    if (response.data.data.length > 0) {
                        for (let i = 0; i < response.data.data.length; i++) {
                            removeFile(response.data.data[i].id)
                            console.log(response.data.data[i].id)
                        }
                    }
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}


const removeFile = (id) => {
    var url = 'framework/Common/removeFile'
    var param = {
        id: id
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
        }
    });
}


const handleRemoveBatch = () => {
    console.log('handleRemoveBatch')

    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要删除的数据!'
        })
        return
    }

    ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        var ids = []
        multipleSelection.value.forEach((item, index) => {
            ids.push(item.id)
        })
        var url = 'pla/OreTestMain/removeBatch'
        var param = {
            ids: JSON.stringify(ids)
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == '0') {
                ElMessage({
                    type: 'success',
                    message: '操作成功!',
                });
                getTableData()
                dialogVisible.value = false
            } else {
                ElMessage({
                    type: 'error',
                    message: '操作失败!' + response.data.msg
                });
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

const handleEditBatch = () => {
    console.log('handleEditBatch')
    if (multipleSelection.value.length != 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一条数据编辑!'
        })
        return
    }
    handleEdit(multipleSelection.value[0])
}



// 附件上传
const dialogVisibleFile = ref(false)
const editFile = (row) => {
    dialogVisibleFile.value = true
    fId.value = row.id
    form.value = row
}
const closeDialogFile = () => {
    dialogVisibleFile.value = false
    getTableDataFile()
    console.log(tableDataFile.value[0])
}
const tableDataFile = ref([])
const getTableDataFile = () => {
    var url = 'framework/Common/queryFile'
    var param = {
        fId: fId.value
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == 0) {
            tableDataFile.value = response.data.data
            console.log(tableDataFile.value)
            if (tableDataFile.value.length > 0) {
                form.value.docNm = tableDataFile.value[0].fileName
            } else {
                form.value.docNm = ''
            }

            proxy.$axios.post('pla/OreTestMain/save', { json: JSON.stringify(form.value), }).then(response => {
                if (response.data.code == 0) {
                    form.value = response.data.data
                    getTableData()
                }
            })
        } else {
            ELMessage({
                type: 'error',
                message: '失败！' + response.data.msg,
            })
        }
    })
}

const handleUpload = () => {
    console.log('handleUpload')
}

const handleDownload = () => {
    console.log('handleDownload')
}

const handleImport = () => {
    console.log('handleImport')
}

const handleExport = () => {
    console.log('handleExport')
}

</script>

<style></style>