import { h, ref, onMounted, reactive, watch, toRaw, nextTick } from "vue";
import { request } from "@/utils/request";
import { useRoute, useRouter } from 'vue-router'
import AddDialog from "./addDialog.vue";
import ScheduleDiaog from "../law/dutyManagement/addDialog.vue"
import DetailDrawer from "./detailDrawer.vue";

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({
    headline: '',
    onset: '',
    expires: '',
    eventType: '',
    weatherSource: '',
    urgency: '',
    areaCodes: [],
});
const INIT_FORM = {
    headline: '',
    onset: '',
    expires: '',
    eventType: '',
    weatherSource: '',
    urgency: '',
    areaCodes: [],
};
// 抽屉内容
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: "headline",
        label: "预警标题",
    },
    {
        // prop: "xxx",
        label: "预警类型",
        formatter: (row) => {
            return h(ElText, { style: {} }, '大雾预警');
        }
    },
    {
        prop: "createTime",
        label: "发送时间",
    },
    {
        prop: "onset",
        label: "生效时间",
    },
    {
        prop: "receiveTime",
        label: "接收时间",
    },
    {
        prop: "forwardTime",
        label: "预警转发时间",
    },
    {
        prop: "expires",
        label: "预警结束时间",
    },
    {
        prop: "affectedRoadSectionCount",
        label: "影响路段",
    },
    {
        prop: "affectedBridgeCount",
        label: "影响桥梁",
    },
    {
        prop: "affectedTunnelCount",
        label: "影响隧道",
    },
    {
        prop: "affectedSlopeCount",
        label: "影响边坡",
    },
    {
        prop: "affectedProjectCount",
        label: "影响项目",
    },
    {
        prop: "responseStatus",
        label: "响应情况",
    },
    {
        label: "操作",
        fixed: "right",
        width: 150,
        render: (row) => () =>
            h("div", { class: "action-btns" }, [
                h(
                    ElButton,
                    {
                        type: "primary",
                        link: true,
                        onClick: async () => {
                            openDetailDrawer(row);
                        },
                    },
                    () => "详情"
                ),
            ]),
    },
]

// 过滤条件
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/lawWeatherWarning/response-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('获取预警列表失败');
        console.error('获取预警列表失败:', error);
    }
}

// 预警类型选项
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 openAddDialog = () => {
    model.title = '发布预警';
    Object.assign(form, INIT_FORM);
    model.props = {
        form: form,
    };
    model.content = AddDialog;
    model.onCancel = () => {
        modelVisible.value = false;
    };
    model.onConfirm = async () => {
        await dialogRef?.value?.dynamicComponentRef?.formRef.validate().then(async () => {
            // console.log('@@@@@发布预警', form);
            await publishWarning(form)
        })
            .catch((err) => {
                ElMessage.error('请处理表单中的错误项');
            });
    };
    model.width = "50%"
    modelVisible.value = true;
}

// 发布预警
const publishWarning = async (data) => {
    try {
        const loading = ElLoading.service({
            lock: true,
            text: '操作中',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        const res = await request({
            url: '/snow-ops-platform/lawWeatherWarning/publish',
            method: 'POST',
            data
        })
        loading.close();
        if (res.code === '00000') {
            ElMessage.success('操作成功');
            modelVisible.value = false;
            getTableData(filterData);

        } else {
            throw new Error(res.message)
        }
    } catch (error) {
        ElMessage.error('操作失败');
        console.error('操作失败:', error);
    }
}

// 打开详情弹窗
const openDetailDrawer = (row) => {
    drawer.title = '预警详情';
    drawer.props = {
        id: row.id,
    };
    drawer.content = DetailDrawer;
    drawerVisible.value = true;
}

// 上传线下帮扶
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('文件上传成功');
        } else {
            throw new Error(res.message || '上传失败');
        }
    } catch (error) {
        ElMessage.error(error.message || '文件上传失败');
        console.error('文件上传失败:', error);
    }
}

const form2 = reactive({});
const INIT_FORM2 = {};

// 排班提交
const addSchedule = async (form) => {
    try {
        const res = await request({
            url: '/snow-ops-platform/law-duty/schedule',
            method: "POST",
            data: form
        })
        if (res.code === '00000') {
            ElMessage.success('排班成功');
            modelVisible.value = false;
            getTableData(filterData)
        } else {
            throw new Error(res.message)
        }
    } catch (error) {
        ElMessage.error('排班失败');
        console.error('排班失败:', error);
    }
}

const openScheduleDiaog = () => {
    model.title = '立即排班';
    Object.assign(form2, INIT_FORM2);
    model.props = {
        form: form2,
    };
    model.content = ScheduleDiaog;
    model.onCancel = () => {
        modelVisible.value = false;
    };
    model.onConfirm = async () => {
        await dialogRef?.value?.dynamicComponentRef?.formRef.validate().then(async () => {
            await addSchedule(form)
            // await publishWarning(form)
        })
            .catch((err) => {
                ElMessage.error('请处理表单中的错误项');
            });
    };
    model.width = "70%"
    modelVisible.value = true;
}





export default () => {

    const router = useRouter();
    // 跳转到台账页面
    const gotoLedgerPage = () => {
        router.push({
            path: '/ledgerManagement3'
        });
    };
    // 跳转到值班管理
    const gotoDutyPage = () => {
        router.push({
            path: '/dutyManagement'
        });
    };

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


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



    return {
        tableData,
        filterData,

        eventTypeOptions,
        severityOptions,
        responseOptions,

        pagination,
        columns,
        gotoLedgerPage,
        gotoDutyPage,

        modelVisible,
        model,
        drawerVisible,
        drawer,
        dialogRef,
        drawerRef,
        openAddDialog,
        openScheduleDiaog,

        uploadFile,
    }
}