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";

const tableData = ref([]); // 表格数据
const modelVisible = ref(false); // 弹窗状态
const drawerVisible = ref(false); // 抽屉状态
// 弹窗内容
const model = reactive({

});
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: "userCount",
        label: "值班人数",
    },
    {
        prop: "startTime",
        label: "开始时间",
    },
    {
        prop: "endTime",
        label: "结束时间",
    },
    {
        prop: "createTime",
        label: "排班时间",
    },
    {
        prop: "createBy",
        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/law-duty/page',
            method: "GET",
            params: {
                dutyStartTime: filteredParams.timeRange?.[0],
                dutyEndTime: filteredParams.timeRange?.[1],
                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 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 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 () => {
            await addSchedule(form)
            // await publishWarning(form)
        })
            .catch((err) => {
                ElMessage.error('请处理表单中的错误项');
            });
    };
    model.width = "70%"
    modelVisible.value = true;
}

export default () => {

    const router = useRouter();

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


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



    return {
        tableData,
        filterData,

        pagination,
        columns,

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