<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" :width="480" :close-on-click-modal="false" @closed="$emit('closed', isDel)">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <template v-if="props.projectId != 1">
                <el-form-item label="所属项目" prop="projectId">
                    <el-select v-model="form.projectId" filterable placeholder="请选择所属项目" @change="form.mountedId = 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-form-item label="设备安装点" prop="mountedId">
                    <el-select v-model="form.mountedId" filterable placeholder="请选择设备安装点">
                        <el-option v-for="item in filterMounteds" :key="item.id" :label="item.mountedName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </template>
            <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" placeholder="请选择抓拍时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="抓拍图片" prop="fileData">
                <sc-upload v-model="form.fileData" :width="240" :height="143" drag cropper @removeSuccess="removeSuccess"></sc-upload>
            </el-form-item>
        </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 XEUtils from "xe-utils";
import API from "@/api";
import TOOL from "@/utils/tool";
import scUpload from "@/components/scUpload/minio";

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,
    mountedId: null,
    recordType: "AIHAZARD_REC_ILLEGAL_ENTRY",
    createTime: null,
    features: {},
    fileData: {}
});
const rules = reactive({
    projectId: [{ required: true, message: "请选择所属项目" }],
    mountedId: [{ required: true, message: "请选择设备安装点" }],
    createTime: [{ required: true, message: "请选择抓拍时间" }],
    fileData: [{ required: true, validator: (rule, value, callback) => {
        if (XEUtils.isEmpty(value)) return callback(new Error("请上传抓拍图片"));
        callback();
    }}]
})

const mounteds = ref([]);
const filterMounteds = computed(() => form.value.projectId ? XEUtils.filter(mounteds.value, item => item.projectId == form.value.projectId) : []);
const fetchMounted = async () => {
    const res = await API.aihazard.mounted.get();
    mounteds.value = res || [];
    if (props.projectId == 1) form.value.mountedId = XEUtils.get(XEUtils.find(res, item => item.projectId == 1), "id");
}

const open = () => {
    visible.value = true;
    fetchMounted();
}
const setData = data => {
    open();
    mode.value = "edit";
    XEUtils.objectEach(XEUtils.omit(form.value, "fileData"), (_, key) => {
        if (key == "features") {
            const features = XEUtils.toStringJSON(XEUtils.get(data, key, "{}"));
            const path = XEUtils.get(features, "bigImage.image", "");
            
            path && XEUtils.set(form.value, "fileData", { path });
            XEUtils.set(form.value, key, features);
        } else XEUtils.set(form.value, key, XEUtils.get(data, key));
    });
}

const formRef = ref();
const submit = () => {
    formRef.value.validate(valid => {
        if (valid) {
            const data = XEUtils.omit(form.value, "features", "fileData");
            const features = XEUtils.clone(form.value.features);
            XEUtils.set(features, "bigImage.image", form.value.fileData.path);
            XEUtils.set(data, "features", XEUtils.toJSONString(features));

            isSaving.value = true;
            API.aihazard.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 features = XEUtils.clone(form.value.features);
        XEUtils.set(features, "bigImage.image", "");
        
        const data = {
            id: form.value.id,
            mountedId: form.value.mountedId,
            features: XEUtils.toJSONString(features)
        }
        
        isDel.value = true;
        API.aihazard.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>