import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import { request } from "@/utils/request";
import { useRoute, useRouter } from 'vue-router'

const tableData = ref([]); // 表格数据

const modelVisible = ref(false); // 弹窗状态
const drawerVisible = ref(false); // 抽屉状态
// 弹窗内容
const model = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    width: '',
});
const form = reactive({
});
const INIT_FORM = {

};
// 抽屉内容
const drawer = reactive({
    title: '',
    content: null,
    props: {},
    onCancel: null,
    onConfirm: null,
    direction: 'rtl',
    size: '50%'
});
const dialogRef = ref(null); // 弹窗实例
const drawerRef = ref(null); // 抽屉实例

const columns = [
    {
        prop: "helpTime",
        label: "帮扶时间",
        // formatter: (row) => `${row.helpTime || ''} - ${row.helpTimeEnd || ''}`,
    },
    {
        prop: "helpCounty",
        label: "帮扶区县",
    },
    {
        prop: "helpPerson",
        label: "帮扶人员",
    },
    {
        prop: "helpUnit",
        label: "帮扶单位",
    },
    {
        prop: "helpStatus",
        label: "帮扶情况",
    },
    {
        prop: "attachmentUrl",
        label: "附件",
        render: (row) => {
            if (row.attachmentUrl) {
                return h(ElButton, {
                    text: 'true',
                    type: 'primary',
                    onClick: () => downloadAttachment(row.attachmentUrl)
                }, '附件下载');
            } else {
                return h('span', {}, '---');
            }
        }
    },
    {
        prop: "uploadTime",
        label: "上传时间",
    },
    {
        prop: "remark",
        label: "备注",
    },
]

// 过滤条件
const filterData = reactive({})
// 分页
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizes: [10, 20, 50],
    layout: "prev, pager, next, jumper",
    onChange: (page, pageSize) => {
        pagination.current = page;
        pagination.pageSize = pageSize;
        getTableData(filterData);
    },
});

// 获取列表
const getTableData = async (filterData = {}) => {
    try {
        // 过滤空字符串属性
        const filteredParams = {};
        Object.keys(filterData).forEach(key => {
            if (filterData[key] !== '' && filterData[key] != null) {
                filteredParams[key] = filterData[key];
            }
        });
        const res = await request({
            url: '/snow-ops-platform/fgc-xxbf/list',
            method: "GET",
            params: {
                ...filteredParams,
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
            }
        })
        if (res.code === '00000') {
            tableData.value = res.data.records
            pagination.total = res.data.total
        } else {
            throw new Error(res.message)
        }
    } catch (error) {
        ElMessage.error(error.message)
        console.error('获取列表失败:', error);
    }
}

// 下载附件
const downloadAttachment = (url) => {
    if (!url) {
        ElMessage.warning('无附件地址');
        return;
    }
    // 直接使用 window.open 触发下载
    window.open(url, '_blank');
}

// 预警类型选项
const eventTypeOptions = [
    { label: "全部", value: "" },
    { label: "台风预警", value: "台风预警" },
    { label: "暴雨预警", value: "暴雨预警" },
    { label: "寒潮预警", value: "寒潮预警" },
    { label: "大雾预警", value: "大雾预警" },
    { label: "暴雪预警", value: "暴雪预警" },
    { label: "道路结冰预警", value: "道路结冰预警" },
    { label: "雷电预警", value: "雷电预警" },
    { label: "强对流预警", value: "强对流预警" },
];

// 预警级别选项
const severityOptions = [
    { label: "全部", value: "" },
    { label: "红色预警", value: "红色预警" },
    { label: "橙色预警", value: "橙色预警" },
    { label: "黄色预警", value: "黄色预警" },
    { label: "蓝色预警", value: "蓝色预警" },
]

// 响应情况选项
const responseOptions = [
    { label: "全部", value: "" },
    { label: "未响应", value: "未响应" },
    { label: "部分响应", value: "部分响应" },
    { label: "全部响应", value: "全部响应" },
]


const downloadFile = async () => {
    window.open('/snow-ops-platform/fgc-xxbf/template', '_blank');
}

const uploadFile = async (file) => {
    if (!file) {
        ElMessage.warning('请选择要上传的文件');
        return;
    }

    try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);

        const loading = ElLoading.service({
            lock: true,
            text: '操作中',
            background: 'rgba(0, 0, 0, 0.7)',
        })

        // 发送POST请求
        const res = await request({
            url: '/snow-ops-platform/fgc-xxbf/upload',
            method: 'POST',
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });

        // 关闭加载提示
        loading.close();

        if (res.code === '00000') {
            ElMessage.success('文件上传成功');
            // 刷新表格数据
            getTableData(filterData);
        } else {
            throw new Error(res.message || '上传失败');
        }
    } catch (error) {
        ElMessage.error(error.message || '文件上传失败');
        console.error('文件上传失败:', error);
    }
}


export default () => {

    onMounted(() => {
        getTableData();
    })


    watch(filterData, (val) => {
        getTableData(filterData);
    }, { deep: true })


    return {
        modelVisible,
        model,
        drawerVisible,
        drawer,
        dialogRef,
        drawerRef,

        eventTypeOptions,
        severityOptions,
        responseOptions,


        tableData,
        filterData,
        pagination,
        columns,

        downloadFile,
        uploadFile,


    }
}