<template>
    <el-dialog v-model="visible" title="数据模拟" fullscreen :close-on-click-modal="false" @closed="$emit('closed')">
        <el-tabs v-model="apiKey">
            <el-tab-pane label="参数配置" name="makeData"></el-tab-pane>
            <el-tab-pane label="数据复制" name="copyData" disabled></el-tab-pane>
        </el-tabs>

        <el-form ref="formRef" :model="form" :rules="rules" label-width="126">
            <el-row>
                <el-col :md="12" :xs="24">
                    <el-form-item label="模拟项目" prop="targetProjectId">
                        <el-select v-model="form.targetProjectId" filterable placeholder="请选择模拟项目" @change="form.targetMountedId = null, dataTimeRange()">
                            <el-option v-for="item in $TOOL.data.get('PROJECT')" :key="item.fpiId" :label="item.projectName" :value="item.fpiId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col v-if="form.targetProjectId" :md="12" :xs="24">
                    <el-form-item label="数据时间范围">
                        <template v-if="XEUtils.isEmpty(acceptItem)">该项目未配置应用项，<el-button type="primary" link @click="$router.push('/project/acceptItems')">去配置</el-button></template>
                        <template v-else-if="acceptItem.beginTime">{{ $TOOL.dateFormat(acceptItem.beginTime, "YY.M.D") }}<span>-{{ acceptItem.endTime && $TOOL.dateFormat(acceptItem.endTime, "YY.M.D") || "至今" }}</span></template>
                        <template v-else>该项目未配置数据时间范围，<el-button type="primary" link @click="$router.push('/project/maintenance')">去配置</el-button></template>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="广播任务" prop="targetTaskId">
                        <el-select v-model="form.targetTaskId" filterable placeholder="请选择模拟项目广播任务">
                            <el-option v-for="item in filterTasks" :key="item.id" :label="item.taskName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="模拟时间范围" prop="targetTime">
                        <el-date-picker v-model="form.targetTime" type="daterange" :clearable="false" value-format="YYYY-MM-DD 00:00:00" :shortcuts="shortcuts" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :md="12" :xs="24">
                    <el-form-item class="step-item" label="播放时长" prop="timeSeconds">
                        <el-input-number v-model="form.timeSeconds" :min="0" :controls="false" placeholder="播放时长"></el-input-number>

                        <el-radio-group v-model="form.timeStepType" @change="stepTypeChange">
                            <el-radio value="second">秒</el-radio>
                            <el-radio value="minute">分钟</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

                <el-col :md="12" :xs="24">
                    <el-form-item label="数据处理" prop="isCover">
                        <el-radio-group v-model="form.isCover">
                            <el-radio :value="false">重复新增</el-radio>
                            <el-radio :value="true">数据覆盖</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit()">提交</el-button>
            <el-button v-if="form.source == 'other'" :loading="isSaving" type="primary" auto-insert-space @click="submit('template')">保存为模版</el-button>
            <el-button auto-insert-space @click="visible = false">取消</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import XEUtils from "xe-utils";
import API from "@/api";
import TOOL from "@/utils/tool";
import { rangeShortcuts } from "@/utils/shortcuts";

const route = useRoute();
const $emit = defineEmits(["success", "closed"]);
const apiKey = ref("makeData");
const visible = ref(false);
const isSaving = ref(false);

const shortcuts = rangeShortcuts("YYYY-MM-DD 00:00:00");
const form = ref({
    targetProjectId: TOOL.data.get("PROJECT_ID"),
    targetMountedId: null,
    targetTaskId: null,
    targetTime: [],
    timeSeconds: 20,
    timeStepType: "minute",
    isCover: false
});

const rules = reactive({
    targetProjectId: [{ required: true, message: "请选择模拟项目" }],
    targetTaskId: [{ required: true, message: "请选择模拟项目广播任务" }],
    targetTime: [{ required: true, message: "请选择模拟时间范围" }],
    timeSeconds: [{ required: true, message: "请输入播放时长" }],
    isCover: [{ required: true }]
});

const acceptItem = ref({});
const dataTimeRange = async () => {
    const query = {
        projectId: form.value.targetProjectId,
        itemName: XEUtils.last(route.meta.title.split("-"))
    }
    const res = await API.project.info.bindItem.judgment(query);
    acceptItem.value = res || {};
}

const tasks = ref([]);
const filterTasks = computed(() => form.value.targetProjectId ? XEUtils.filter(tasks.value, item => item.projectId == form.value.targetProjectId) : []);
const fetchTask = async () => {
    const res = await API.broadcast.task.get();
    tasks.value = res || [];
}

const open = () => {
    visible.value = true;
    TOOL.data.get("PROJECT_ID") && dataTimeRange();
    fetchTask();
}

const stepTypeChange = e => {
    if (e == "minute") XEUtils.set(form.value, "timeSeconds", XEUtils.floor(XEUtils.divide(form.value.timeSeconds, 60)));
    if (e == "second") XEUtils.set(form.value, "timeSeconds", XEUtils.multiply(form.value.timeSeconds, 60));
}

const formRef = ref();
const submit = key => {
    formRef.value.validate(valid => {
        if (valid) {
            const data = XEUtils.omit(form.value, "targetTime", "timeStepType");
            XEUtils.set(data, "targetMountedId", XEUtils.get(XEUtils.find(tasks.value, item => item.id == form.value.targetTaskId), "mountedId"));
            XEUtils.set(data, "targetBeginTime", XEUtils.first(form.value.targetTime));
            XEUtils.set(data, "targetEndTime", XEUtils.last(form.value.targetTime));
            XEUtils.set(data, "timeSeconds", form.value.timeStepType == "minute" ? XEUtils.multiply(form.value.timeSeconds, 60) : form.value.timeSeconds);
            
            isSaving.value = true;
            API.broadcast.dataMock[apiKey.value](data).then(() => {
                isSaving.value = false;
                ElMessage.success("操作成功");
                visible.value = false;
                $emit("success");
            }).catch(() => isSaving.value = false);
        } else {
            return false;
        }
    });
}

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.el-form {margin-top: 5px;padding-right: var(--el-message-close-size, 16px);}
.el-form-item .el-radio-group {flex-wrap: nowrap;}

.el-form-item .el-input-number {width: 100%;}
.el-form-item .el-input-number :deep(.el-input__prefix) {margin-right: 8px;}
.el-form-item .el-input-number :deep(.el-input__inner) {text-align: unset;}

.el-form-item.step-item {
    .el-input-number {flex: 1;}
    .el-radio-group {margin-left: 20px;}
}
</style>