<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" :width="860" :close-on-click-modal="false" @closed="$emit('closed', isDel)">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <el-row v-if="props.projectId != 1">
                <el-col :md="12" :xs="24">
                    <el-form-item label="所属项目" prop="projectId">
                        <el-select v-model="form.projectId" filterable placeholder="请选择所属项目" @change="form.gateId = null">
                            <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="gateId">
                        <el-select v-model="form.gateId" filterable placeholder="请选择场区闸口">
                            <el-option v-for="item in filterGates" :key="item.id" :label="item.gateName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :md="12" :xs="24">
                    <el-form-item label="车牌号" prop="plate">
                        <el-input v-model="form.plate" :formatter="value => value.toUpperCase()" placeholder="请输入车牌号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="车牌颜色" prop="color">
                        <el-select v-model="form.color" filterable placeholder="请选择车牌颜色">
                            <el-option v-for="(label, key) in plateColorDic" :key="key" :label="label" :value="key"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="事件类型" prop="event">
                        <el-select v-model="form.event" filterable placeholder="请选择事件类型">
                            <el-option v-for="(label, key) in eventDic" :key="key" :label="label" :value="key"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="抓拍时间" prop="createTime">
                        <el-date-picker v-model="form.createTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="date => moment(date).hour() > 5 && moment(date).hour() < 18" :disabled-hours="() => Array.from({ length: 12 }, (_, i) => i + 6)" placeholder="请选择抓拍时间"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24">
                    <el-form-item label="抓拍图片" prop="fileData">
                        <sc-upload v-model="form.fileData" apiKey="parking" :width="240" :height="143" drag cropper @removeSuccess="removeSuccess"></sc-upload>
                    </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 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 { plateColorDic, eventDic, formatMeta } from "@/views/dataMock/parking/main";
import scUpload from "@/components/scUploadMinio/index";

const $emit = defineEmits(["success", "closed"]);
const props = defineProps({
    projectId: { type: Number, default: TOOL.data.get("PROJECT_ID") }
});

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

const mode = ref("add");
const titleMap = reactive({
    add: "数据录入",
    edit: "修改"
});

const form = ref({
    id: null,
    projectId: props.projectId,
    gateId: null,
    plate: null,
    color: null,
    event: null,
    createTime: null,
    features: "{}",
    metaFeatures: {},
    fileData: {}
});
const rules = reactive({
    projectId: [{ required: true, message: "请选择所属项目" }],
    gateId: [{ required: true, message: "请选择场区闸口" }],
    plate: [{ required: true, message: "请输入车牌号" }],
    color: [{ required: true, message: "请选择车牌颜色" }],
    event: [{ required: true, message: "请选择事件类型" }],
    createTime: [{ required: true, message: "请选择抓拍时间" }],
    fileData: [{ required: true, validator: (rule, value, callback) => {
        if (XEUtils.isEmpty(value)) return callback(new Error("请上传抓拍图片"));
        callback();
    }}]
})

const gates = ref([]);
const filterGates = computed(() => form.value.projectId ? XEUtils.filter(gates.value, item => item.projectId == form.value.projectId) : []);
const fetchGate = async () => {
    const res = await API.parking.gate.get();
    gates.value = res || [];
    if (props.projectId == 1) form.value.gateId = XEUtils.get(XEUtils.find(res, item => item.projectId == 1), "id");
}

const open = () => {
    visible.value = true;
    fetchGate();
}
const setData = data => {
    open();
    mode.value = "edit";
    XEUtils.objectEach(XEUtils.omit(form.value, "fileData"), (_, key) => {
        if (key == "metaFeatures") {
            if (formatMeta(data).url) {
                XEUtils.set(form.value, "fileData", {
                    metaKey: formatMeta(data).metaKey,
                    path: formatMeta(data).url
                })
            }

            XEUtils.set(form.value, key, XEUtils.toStringJSON(XEUtils.get(data, key, "{}")));
        } else XEUtils.set(form.value, key, XEUtils.get(data, key));
    });
}

const formRef = ref();
const submit = () => {
    formRef.value.validate(valid => {
        if (valid) {
            const metaKey = XEUtils.get(form.value, "fileData.metaKey", "imageFile");
            const data = XEUtils.omit(form.value, "metaFeatures", "fileData");
            const metaFeatures = XEUtils.clone(form.value.metaFeatures);

            XEUtils.set(metaFeatures, `request.AlarmInfoPlate.result.PlateResult.${metaKey}`, form.value.fileData.path);
            XEUtils.set(data, "metaFeatures", XEUtils.toJSONString(metaFeatures));

            isSaving.value = true;
            API.parking.record[mode.value](data).then(() => {
                isSaving.value = false;
                ElMessage.success("操作成功");
                isDel.value = false;
                visible.value = false;
                $emit("success", mode.value);
            }).catch(() => isSaving.value = false);
        } else {
            return false;
        }
    });
}

const removeSuccess = () => {
    if (form.value.id) {
        const metaKey = XEUtils.get(form.value, "fileData.metaKey", "imageFile");
        const metaFeatures = XEUtils.clone(form.value.metaFeatures);
        XEUtils.set(metaFeatures, `request.AlarmInfoPlate.result.PlateResult.${metaKey}`, "");
        
        const data = {
            id: form.value.id,
            gateId: form.value.gateId,
            metaFeatures: XEUtils.toJSONString(metaFeatures)
        }
        
        isDel.value = true;
        API.parking.record.edit(data);
    }
}

defineExpose({
    open,
    setData
})
</script>

<style scoped>
.el-form {
    padding-right: calc(var(--el-dialog-padding-primary) + var(--el-message-close-size, 16px));
}
</style>