<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" disabled></el-tab-pane>
            <el-tab-pane label="数据复制" name="copyData"></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.targetGateId = 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="targetGateId">
                        <el-select v-model="form.targetGateId" filterable placeholder="请选择模拟场区闸口" @change="targetGateChange">
                            <el-option v-for="item in filterTargetG" :key="item.id" :label="item.gateName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item class="range-item" label="模拟时间范围" prop="targetBeginTime">
                        <el-date-picker v-model="form.targetBeginTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" :default-time="new Date()" placeholder="请选择模拟数据开始时间" @change="dateChange"></el-date-picker>
                        <span>至</span>
                        <el-input v-model="form.targetEndTime" readonly placeholder="模拟数据结束时间">
                            <template #prefix><sc-iconify icon="ep:clock"></sc-iconify></template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="数据来源" prop="source">
                        <el-radio-group v-model="form.source" @change="refreshTable">
                            <el-radio value="template">模版项目</el-radio>
                            <el-radio value="other">其他项目</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-divider style="margin-top: 6px;" />

            <el-row>
                <template v-if="form.source == 'other'">
                    <el-col :md="12" :xs="24">
                        <el-form-item label="数据源项目" prop="sourceProjectId">
                            <el-select v-model="form.sourceProjectId" filterable placeholder="请选择数据源项目" @change="form.sourceGateId = null, refreshTable()">
                                <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 :md="12" :xs="24">
                        <el-form-item label="数据源闸口" prop="sourceGateId">
                            <el-select v-model="form.sourceGateId" filterable placeholder="请选择数据源闸口" @change="refreshTable">
                                <el-option v-for="item in filterSourceG" :key="item.id" :label="item.gateName" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </template>

                <el-col :md="12" :xs="24">
                    <el-form-item label="抓拍时间" prop="sourceTime">
                        <el-date-picker v-model="form.sourceTime" type="datetimerange" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" :shortcuts="shortcuts" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" @change="dateChange(), refreshTable()"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <data-table ref="tableRef" :isTemp="form.source == 'template'" hideHandler :options="tableOptions"></data-table>
        </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 moment from "moment";
import XEUtils from "xe-utils";
import API from "@/api";
import TOOL from "@/utils/tool";
import { rangeShortcuts } from "@/utils/shortcuts";
import { transferType } from "./main";
import dataTable from "./components/record";

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

const shortcuts = rangeShortcuts();
const form = ref({
    targetProjectId: TOOL.data.get("PROJECT_ID"),
    targetGateId: null,
    targetEventType: null,
    targetBeginTime: null,
    targetEndTime: null,
    isCover: false,
    source: "other",
    sourceProjectId: null,
    sourceProjectIdNot: 1,
    applySql: "(day_seconds >= 64800 and day_seconds <= 86399) or (day_seconds >=0 and day_seconds <= 21599)",
    sourceGateId: null,
    sourceTime: [moment().startOf("month").format("YYYY-MM-DD HH:mm:ss"), moment().format("YYYY-MM-DD HH:mm:ss")]
});

const rules = reactive({
    targetProjectId: [{ required: true, message: "请选择模拟项目" }],
    targetGateId: [{ required: true, message: "请选择模拟场区闸口" }],
    targetBeginTime: [{ required: true, message: "请选择模拟数据开始时间" }],
    isCover: [{ required: true }],
    source: [{ required: true }],
    sourceProjectId: [{ required: true, message: "请选择数据源项目" }],
    sourceGateId: [{ required: true, message: "请选择数据源闸口" }],
    sourceTime: [{ required: true, message: "请选择数据源抓拍时间" }]
})

const tableRef = ref();
const tableOptions = reactive({
    batchDel: false,
    maxHeight: 1048,
    toolbarConfig: { enabled: true, print: false, zoom: false },
    formConfig: { enabled: false, data: form },
    paramsColums: computed(() => [
        { column: "projectId", field: form.value.source == "template" ? "sourceProjectIdNot" : "sourceProjectId"  },
        form.value.source == "template" ? {} : { column: "projectIdNot", field: "sourceProjectIdNot" },
        { column: "gateId", field: "sourceGateId" },
        { column: "applySql" },
        { column: "createTimeBegin", field: "sourceTime[0]" },
        { column: "createTimeEnd", field: "sourceTime[1]" }
    ])
})
const refreshTable = () => tableRef.value.refreshTable();

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 gates = ref([]);
const filterTargetG = computed(() => form.value.targetProjectId ? XEUtils.filter(gates.value, item => item.projectId == form.value.targetProjectId) : []);
const filterSourceG = computed(() => form.value.sourceProjectId ? XEUtils.filter(gates.value, item => item.projectId == form.value.sourceProjectId) : []);
const fetchGate = async () => {
    const res = await API.parking.gate.get();
    gates.value = res || [];
}

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

const targetGateChange = id => form.value.targetEventType = XEUtils.get(transferType, XEUtils.get(XEUtils.find(gates.value, item => item.id == id), "gateType"));

const dateChange = () => {
    if (form.value.sourceTime && form.value.sourceTime.length && form.value.targetBeginTime) form.value.targetEndTime = moment(form.value.targetBeginTime).add(moment(XEUtils.last(form.value.sourceTime)).diff(XEUtils.first(form.value.sourceTime))).format("YYYY-MM-DD HH:mm:ss")
    else form.value.targetEndTime = null;
}

const formRef = ref();
const submit = key => {
    formRef.value.validate(valid => {
        if (valid) {
            if (tableRef.value?.getTableTotal() == 0) return ElMessage.warning("暂无相关数据，请调整条件后重试。");
            
            const data = XEUtils.omit(form.value, "sourceProjectId", "sourceProjectIdNot", "applySql", "source", "sourceTime");
            XEUtils.set(data, "sourceBeginTime", XEUtils.first(form.value.sourceTime));
            XEUtils.set(data, "sourceEndTime", XEUtils.last(form.value.sourceTime));
            
            form.value.source == "template" && XEUtils.set(data, "sourceGateId", XEUtils.get(XEUtils.find(gates.value, item => item.projectId == 1), "id"));
            if (key == "template") {
                XEUtils.set(data, "targetProjectId", 1);
                XEUtils.set(data, "targetGateId", XEUtils.get(XEUtils.find(gates.value, item => item.projectId == 1), "id"));
            }

            isSaving.value = true;
            API.parking.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 .range-item :deep(.el-form-item__content) {
    .el-date-editor, .el-input {flex: 1;}
    .el-date-editor + span {padding: 0 10px;}
}

.el-form :deep(.el-main) {padding-right: 0;padding-bottom: 0;}
</style>