<template>
    <el-dialog v-model="visible" title="数据模拟" fullscreen :close-on-click-modal="false" @closed="$emit('closed')">
        <el-tabs v-model="dataSouce" @tab-change="apiKey = dataSouce == 'normal' ? 'copyData' : 'makeData'">
            <el-tab-pane label="标准数据" name="normal"></el-tab-pane>
            <el-tab-pane label="报警数据" name="alarm"></el-tab-pane>
            <el-tab-pane label="考勤数据" name="attendance"></el-tab-pane>
        </el-tabs>

        <el-tabs v-model="apiKey">
            <el-tab-pane label="参数配置" name="makeData" :disabled="dataSouce == 'normal'"></el-tab-pane>
            <el-tab-pane label="数据复制" name="copyData" :disabled="dataSouce == 'alarm' || dataSouce == 'attendance'"></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('/basic/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('/basic/project')">去配置</el-button></template>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="模拟项目安装点" prop="targetMountedId">
                        <el-select v-model="form.targetMountedId" filterable placeholder="请选择模拟项目安装点">
                            <el-option v-for="item in filterTargetM" :key="item.id" :label="item.mountedName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <template v-if="dataSouce == 'normal'">
                    <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(2000, 1, 1, 23, 59, 59)" 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="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-col :md="12" :xs="24">
                        <el-form-item style="margin-bottom: 0;" 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>
                </template>

                <template v-if="dataSouce == 'alarm'">
                    <el-col :md="12" :xs="24">
                        <el-form-item label="模拟时间范围" prop="targetTime">
                            <el-date-picker v-model="form.targetTime" 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="结束时间"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :md="12" :xs="24">
                        <el-form-item label="报警条数" prop="warnNum">
                            <el-input-number v-model="form.warnNum" :min="0" :controls="false" placeholder="请输入报警条数"></el-input-number>
                        </el-form-item>
                    </el-col>
                </template>

                <template v-if="dataSouce == 'attendance'">
                    <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 label="人员身份证号" prop="personIdCard">
                            <el-input v-model="form.personIdCard" placeholder="请输入人员身份证号"></el-input>
                        </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>
                </template>
            </el-row>

            <template v-if="dataSouce == 'normal'">
                <el-divider />

                <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.sourceMountedId = 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="sourceMountedId">
                                <el-select v-model="form.sourceMountedId" filterable placeholder="请选择数据源安装点" @change="refreshTable">
                                    <el-option v-for="item in filterSourceM" :key="item.id" :label="item.mountedName" :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)]" 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>
            </template>
        </el-form>

        <template #footer>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit()">提交</el-button>
            <el-button v-if="dataSouce == 'normal' && 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 { verifyIdCard } from "@/utils/verificate";
import dataTable from "./components/record";

const route = useRoute();
const $emit = defineEmits(["success", "closed"]);
const dataSouce = ref("normal");
const apiKey = ref("copyData");

const visible = ref(false);
const isSaving = ref(false);

const shortcuts = rangeShortcuts();
const form = ref({
    targetProjectId: TOOL.data.get("PROJECT_ID"),
    targetMountedId: null,
    targetBeginTime: null,
    targetEndTime: null,
    targetTime: [],
    isCover: false,
    source: "other",
    warnNum: null,
    personIdCard: null,
    sourceProjectId: null,
    sourceProjectIdNot: 1,
    sourceMountedId: null,
    sourceTime: [moment().startOf("day").format("YYYY-MM-DD HH:mm:ss"), moment().format("YYYY-MM-DD HH:mm:ss")]
});

const rules = reactive({
    targetProjectId: [{ required: true, message: "请选择模拟项目" }],
    targetMountedId: [{ required: true, message: "请选择模拟项目安装点" }],
    targetBeginTime: [{ required: true, message: "请选择模拟数据开始时间" }],
    targetTime: [
        { required: true, message: "请选择模拟时间范围" },
        { validator: (rule, value, callback) => {
            if (dataSouce.value == "alarm" && moment(XEUtils.last(value)).diff(XEUtils.first(value), "minute") < 5) {
                callback(new Error("模拟时间范围至少为5分钟"));
            } else callback();
        }}
    ],
    isCover: [{ required: true }],
    source: [{ required: true }],
    warnNum: [{ required: true, message: "请输入报警条数" }],
    personIdCard: [
        { required: true, message: "请输入人员身份证号" },
        { validator: (rule, value, callback) => verifyIdCard(rule, value, callback) }
    ],
    sourceProjectId: [{ required: true, message: "请选择数据源项目" }],
    sourceMountedId: [{ 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: "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.system.project.bindItem.judgment(query);
    acceptItem.value = res || {};
}

const mounteds = ref([]);
const filterTargetM = computed(() => form.value.targetProjectId ? XEUtils.filter(mounteds.value, item => item.projectId == form.value.targetProjectId) : []);
const filterSourceM = computed(() => form.value.sourceProjectId ? XEUtils.filter(mounteds.value, item => item.projectId == form.value.sourceProjectId) : []);
const fetchMounted = async () => {
    const res = await API.tower.mounted.get();
    mounteds.value = res || [];
}

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

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), "millisecond"), "millisecond").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("暂无相关数据，请调整条件后重试。");
            
            let data = XEUtils.omit(form.value, "sourceProjectId", "sourceProjectIdNot", "targetTime", "source", "warnNum", "sourceTime");
            if (dataSouce.value == "normal") {
                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, "sourceMountedId", XEUtils.get(XEUtils.find(mounteds.value, item => item.projectId == 1), "id"));
                if (key == "template") {
                    XEUtils.set(data, "targetProjectId", 1);
                    XEUtils.set(data, "targetMountedId", XEUtils.get(XEUtils.find(mounteds.value, item => item.projectId == 1), "id"));
                }
            }
            if (dataSouce.value == "alarm") {
                data = XEUtils.pick(form.value, "targetProjectId", "targetMountedId", "warnNum");
                XEUtils.set(data, "targetBeginTime", XEUtils.first(form.value.targetTime));
                XEUtils.set(data, "targetEndTime", XEUtils.last(form.value.targetTime));
            }

            if (dataSouce.value == "attendance") {
                data = XEUtils.pick(form.value, "targetProjectId", "targetMountedId", "personIdCard", "isCover");
                XEUtils.set(data, "targetBeginTime", XEUtils.first(form.value.targetTime));
                XEUtils.set(data, "targetEndTime", XEUtils.last(form.value.targetTime));
            }
            
            isSaving.value = true;
            API.tower.dataMock[apiKey.value][dataSouce.value](data).then(() => {
                isSaving.value = false;
                ElMessage.success("操作成功");
                visible.value = false;
                $emit("success", dataSouce.value);
            }).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-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 :deep(.el-main) {padding-right: 0;padding-bottom: 0;}
</style>