<template>
    <div class="app-container p-5">
        <el-form
            :model="queryParams"
            class="main-search"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
        >
            <el-form-item label="区域名称" prop="areaName">
                <el-input
                    v-model="queryParams.areaName"
                    placeholder="请输入区域名称"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="区域状态" prop="areaStatus">
                <el-select
                    v-model="queryParams.areaStatus"
                    placeholder="区域状态"
                    clearable
                    style="width: 240px"
                >
                    <el-option
                        :key="0"
                        label="启用"
                        :value="0"
                    />
                    <el-option
                        :key="1"
                        label="禁用"
                        :value="1"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="handleQuery">
                    搜索
                </el-button>
                <el-button size="mini" @click="resetQuery">
                    重置
                </el-button>
                <el-button
                    type="primary"
                    plain
                    size="mini"
                    @click="handleAddArea"
                >
                    添加新区域
                </el-button>
            </el-form-item>
        </el-form>

        <el-table
            ref="tables"
            v-loading="loading"
            :data="list"
            @selection-change="handleSelectionChange"
            :default-sort="defaultSort"
            @sort-change="handleSortChange"
        >
            <el-table-column label="ID" prop="id" width="60">
                <template #default="scope">
                    <span>{{ showIdLastFour(scope.row.id) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="区域名称"
                align="center"
                prop="areaName"
            />
            <el-table-column
                label="创建时间"
                align="center"
                prop="createTime"
                sortable="custom"
                :sort-orders="['descending', 'ascending']"
                width="180"
            >
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="areaStatus">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.areaStatus"
                        :active-value="0"
                        :inactive-value="1"
                        @change="handleAreaStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template #default="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdateArea(scope.row)"
                    >
                        修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleDeleteArea(scope.row)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改区域对话框 -->
        <el-dialog
            :title="areaTitle"
            v-model="areaOpen"
            class="common-dialog"
            width="800px"
            append-to-body
        >
            <el-form ref="areaFormRef" :model="areaForm" :rules="areaRules" label-width="auto">
                <el-form-item label="区域名称" prop="areaName">
                    <el-input
                        v-model="areaForm.areaName"
                        placeholder="请输入区域名称"
                        maxlength="10"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="areaForm.sort" :min="0" />
                    <div class="form-tips ml-3">数值越小排名越靠前</div>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="areaForm.areaStatus">
                        <el-radio :key="0" :label="0" :value="0">
                            启用
                        </el-radio>
                        <el-radio :key="1" :label="1" :value="1">
                            禁用
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer text-right">
                <el-button type="primary" @click="submitAreaForm">
                    确认
                </el-button>
                <el-button @click="cancelArea">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 模拟 API 调用
const getAreaList = (params) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            const mockResponse = {
                data: [
                    {
                        id: 1,
                        areaName: '区域 1',
                        createTime: '2024-01-01 12:00:00',
                        areaStatus: 0
                    },
                    {
                        id: 2,
                        areaName: '区域 2',
                        createTime: '2024-02-01 12:00:00',
                        areaStatus: 1
                    }
                ],
                total: 2
            };
            resolve(mockResponse);
        }, 1000);
    });
};

const updateAreaStatus = (id, status) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
};

const getAreaInfo = (id) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            const mockResponse = {
                data: {
                    id: 1,
                    areaName: '区域 1',
                    sort: 0,
                    areaStatus: 0
                }
            };
            resolve(mockResponse);
        }, 1000);
    });
};

const saveAreaUpdate = (data) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
};

const addAreaInfo = (data) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
};

const deleteAreaInfo = (id) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
};

// 遮罩层
const loading = ref(true);
// 标题
const areaTitle = ref('');
// 选中数组
const ids = ref([]);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 表格数据
const list = ref([]);
// 是否显示弹出层
const areaOpen = ref(false);
// 默认排序
const defaultSort = ref({ prop: 'id', order: 'descending' });
// 表单参数
const areaForm = ref({
    id: '',
    areaName: '',
    sort: '',
    areaStatus: 0
});

// 查询参数
const queryParams = ref({
    page: 1,
    pageSize: 10,
    areaName: '',
    areaStatus: ''
});

// 表单校验
const areaRules = ref({
    areaName: [
        {
            required: true,
            message: '区域名称为必填项',
            trigger: 'blur'
        },
        {
            min: 2,
            max: 30,
            message: '区域名称长度需在 2 到 30 之间',
            trigger: 'blur'
        }
    ]
});

// 生命周期钩子函数，组件挂载后调用
onMounted(() => {
    getList();
});

// 查询列表
const getList = async () => {
    loading.value = true;
    try {
        const response = await getAreaList(queryParams.value);
        list.value = response.data;
        total.value = response.total;
    } catch (error) {
        console.log('获取列表错误', error);
    } finally {
        loading.value = false;
    }
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.value.page = 1;
    getList();
};
const queryForm = ref(null);

// 重置按钮操作
const resetQuery = () => {
    queryForm.value.resetFields();
    handleQuery();
};

// 区域状态修改
const handleAreaStatusChange = (row) => {
    let text = row.areaStatus === 0? '启用' : '禁用';
    const confirmMsg = `确认更改区域状态为 ${text}，区域名称为 ${row.areaName}？`;
    ElMessageBox.confirm(confirmMsg, '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
      .then(() => {
            return updateAreaStatus(row.id, row.areaStatus);
        })
      .then(() => {
            const successMsg = `状态更改成功，已 ${text}`;
            ElMessage.success(successMsg);
        })
      .catch(() => {
            row.areaStatus = row.areaStatus === 1? 0 : 1;
        });
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.id);
    multiple.value =!selection.length;
};

// 排序触发事件
const handleSortChange = (column, prop, order) => {
    queryParams.value.orderByColumn = column.prop;
    queryParams.value.isAsc = column.order;
    getList();
};

// 新增区域按钮操作
const handleAddArea = () => {
    resetArea();
    areaOpen.value = true;
    areaTitle.value = '添加新区域';
};
const areaFormRef = ref(null);

// 区域表单重置
const resetArea = () => {
    areaForm.value = {
        id: '',
        areaName: '',
        sort: 0,
        areaStatus: 0
    };
    // areaFormRef.value.resetFields();
};

// 取消区域按钮
const cancelArea = () => {
    areaOpen.value = false;
    resetArea();
};
// 提交区域按钮
const submitAreaForm = () => {
    areaFormRef.value.validate((valid) => {
        if (valid) {
            let data = {
                areaName: areaForm.value.areaName,
                sort: areaForm.value.sort,
                areaStatus: areaForm.value.areaStatus
            };
            if (areaForm.value.id) {
                data.id = areaForm.value.id;
                saveAreaUpdate(data)
                  .then(() => {
                        ElMessage.success('修改成功');
                        areaOpen.value = false;
                        getList();
                    })
                  .catch((error) => {
                        console.log('修改错误', error);
                    });
            } else {
                addAreaInfo(data)
                  .then(() => {
                        ElMessage.success('添加成功');
                        areaOpen.value = false;
                        getList();
                    })
                  .catch((error) => {
                        console.log('添加错误', error);
                    });
            }
        }
    });
};

// 修改区域按钮操作
const handleUpdateArea = (row) => {
    resetArea();
    const id = row.id || ids.value;
    getAreaInfo(id)
      .then((response) => {
            areaForm.value = response.data;
            areaOpen.value = true;
            areaTitle.value = '编辑区域';
        })
      .catch((error) => {
            console.log('获取区域信息错误', error);
        });
};

// 删除区域按钮操作
const handleDeleteArea = (row) => {
    const code = row.areaName || areaForm.value.id;
    const confirmMsg = `确认删除区域名称为 ${code} 的区域？`;
    ElMessageBox.confirm(confirmMsg, '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
      .then(async () => {
            try {
                await deleteAreaInfo(row.id);
                ElMessage.success('删除成功');
                getList();
            } catch (error) {
                console.log('删除错误', error);
            }
        })
      .catch(() => {});
};

// 展示 ID 的后四位
const showIdLastFour = (id) => {
    return id.toString().slice(-4);
};

// 解析时间
const parseTime = (time) => {
    return time;
};
</script>

<style scoped>
/* 这里可以添加你的样式 */
</style>    