<template>
    <div class="app-container app-container-bg">
        <el-card class="first-card" ref='firstCard' shadow="always">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.native.prevent>
                <el-form-item label="测站名称" prop="stnm">
                    <el-input v-model="queryParams.stnm" placeholder="请输入测站名称" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['message:value:add']">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['message:value:edit']">修改</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['message:value:remove']">删除</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['message:value:export']">导出</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleBatchEdit">批量设置</el-button>
                </el-col>
                <el-col :span="5">
                    <div class="red mt5" style="display: flex;align-items: center;">
                        <Warning style="width: 1em; height: 1em; margin-right: 8px" />
                        <span>未设置阈值，默认为1小时</span>
                    </div>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
        </el-card>
        <div class="el-card-p card-shadow carder-border mt10 pad10 ">
            <el-table class="table-box" v-table-height v-loading="loading" :data="valueList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :align="alignment" />
                <el-table-column type="index" width="55" :align="alignment" label="序号" />
                <el-table-column label="测站名称" :align="alignment" prop="stnm" />
                <el-table-column label="阈值(h)" :align="alignment" prop="value" />
                <el-table-column label="操作" :align="alignment" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['message:value:edit']">修改</el-button>
                        <el-button text type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['message:value:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.limit" @pagination="getList" />
        </div>
        <el-dialog class="custom-dialog" :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
                <el-form-item label="测站" prop="stnmId">
                    <el-select :multiple="isBatch" clearable collapse-tags v-model="form.stnmId" placeholder="请选择测站" style="width: 100%;">
                        <template #header v-if="isBatch">
                            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="t in stationList" :key="t.stnmId" :label="t.stnm" :value="t.stnmId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="阈值(h)" prop="value">
                    <el-input-number controls-position="right" v-model="form.value" placeholder="请输入阈值" style="width: 100%;" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(formRef)" v-loading='btnLoading'>确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    import { ref, reactive, onMounted, } from 'vue'
    import dayjs from 'dayjs'
    const { proxy } = getCurrentInstance()
    const alignment = 'center'
    const showSearch = ref(true)
    const queryParams = reactive({
        page: 1,
        limit: 10,
        stnm: '',
    })
    const loading = ref(false)
    const total = ref(0)
    const valueList = ref([])
    const getList = async () => {
        loading.value = true;
        try {
            const res = await proxy.axiosGet('/message/value/list', queryParams)
            if (res.code == 0) {
                valueList.value = res.data
                total.value = res.count
            }
        } catch (error) {

        } finally {
            loading.value = false
        }
    }
    const stationList = ref([]);
    const getStationList = async () => {
        let params = {
            sType: 'ALL'
        }
        try {
            let res = await proxy.axiosGet('/basic/info/queryMapStationList', params);
            if (res.code === 0) {
                stationList.value = res.data;
            }
        } catch (error) {
            console.log(error)
        }
    }
    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.pageNum = 1
        getList()
    }
    const resetQuery = () => {
        proxy.resetForm("queryForm");
        handleQuery();
    }

    // 多选框选中数据
    let ids = ref([])
    let names = ref([])
    let single = ref(true)
    let multiple = ref(true)
    const handleSelectionChange = (selection) => {
        ids.value = selection.map(item => item.id)
        names.value = selection.map(item => item.stnm)
        single.value = selection.length !== 1
        multiple.value = !selection.length
    }
    /** 新增按钮操作 */
    const open = ref(false)
    const title = ref("")
    const handleAdd = () => {
        isBatch.value = false
        reset();
        open.value = true;
        title.value = "添加";
    }
    /** 修改按钮操作 */
    const form = reactive({})
    const rules = reactive({})
    const handleUpdate = async (row) => {
        isBatch.value = false
        reset();
        let id = row.id || ids.value
        try {
            let res = await proxy.axiosGet('/message/value/info/' + id);
            if (res.code === 0) {
                Object.assign(form, res.data);
                open.value = true;
                title.value = "修改";
            }
        } catch (error) {
            console.log(error)
        }
    }
    // 批量设置按钮操作
    const checkAll = ref(false)
    const indeterminate = ref(false)
    const isBatch = ref(false)
    const handleBatchEdit = () => {
        isBatch.value = true
        open.value = true;
        title.value = "批量设置";
    }
    watch(form.stnmId, (val) => {
        if (val.length === 0) {
            checkAll.value = false
            indeterminate.value = false
        } else if (val.length === stationList.value.length) {
            checkAll.value = true
            indeterminate.value = false
        } else {
            indeterminate.value = true
        }
    })

    const handleCheckAll = (val) => {
        indeterminate.value = false
        if (val) {
            form.stnmId = stationList.value.map(item => item.stnmId);
        } else {
            form.stnmId = []
        }
        form.stnmId = [...form.stnmId];
    }
    /** 删除按钮操作 */
    const handleDelete = (row) => {
        let stnms = row.stnm || names.value
        const stnmIds = row.id || ids.value;
        proxy.$modal.confirm('是否确认删除测站名称为"' + stnms + '"的数据项？').then(async function () {
            let res = await proxy.axiosDelete('/message/value/delete/' + stnmIds);
            if (res.code === 0) {
                proxy.$modal.msgSuccess("删除成功");
                getList();
            }
        })
    }
    /** 导出按钮操作 */
    const handleExport = async () => {
        proxy.download("message/value/export", {
            ...queryParams.value,
        }, `value_${dayjs(new Date()).format('YYYY-MM-DD')}.xlsx`);
    }
    /*************************************************************  弹窗  ***************************************/
    let formRef = ref(null)
    // 取消按钮
    const cancel = () => {
        open.value = false;
        reset();
    }
    const reset = () => {
        Object.assign(form, {
            id: null,
            name: null,
            deptId: null,
            department: null,
            phone: null,
            remarks: null
        });
        proxy.resetForm("formRef");
    }
    /** 提交按钮 */
    const submitForm = async (formEl) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                if (form.id != null) {
                    editMethod();
                } else {
                    if (isBatch.value) {
                        batchAddMethod()
                    } else {
                        addMethod();
                    }
                }
            }
        })
    }
    // 批量设置
    const batchAddMethod = async () => {
        btnLoading.value = true
        let formBatch = {
            value: form.value,
            stnmIds: form.stnmId.join(','),
        }
        try {
            let res = await proxy.axiosPost('/message/value/batchEdit', formBatch);
            if (res.code === 0) {
                proxy.$modal.msgSuccess("批量设置成功");
                open.value = false;
                getList();
                btnLoading.value = false
            }
        } catch (error) {
            btnLoading.value = false
        }
    }
    const btnLoading = ref(false)
    // 新增方法
    const addMethod = async () => {
        btnLoading.value = true
        try {
            let res = await proxy.axiosPost('/message/value/add', form);
            if (res.code === 0) {
                proxy.$modal.msgSuccess("新增成功");
                open.value = false;
                getList();
                btnLoading.value = false
            }
        } catch (error) {
            btnLoading.value = false
        }
    }
    // 修改方法
    const editMethod = async () => {
        btnLoading.value = true
        try {
            let res = await proxy.axiosPost('/message/value/edit', form);
            if (res.code === 0) {
                proxy.$modal.msgSuccess("修改成功");
                open.value = false;
                getList();
                btnLoading.value = false
            }
        } catch (error) {
            btnLoading.value = false
        }
    }
    onMounted(() => {
        getList()
        getStationList()
    })
</script>