<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { setDocxSave, getDocxDetail } from "@/api/mock.js";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const user = JSON.parse(proxy.$vtk.storage.get("_mis_acis_users"));
const date = proxy.$vtk.filters.date;

const breadcrumbItems = [
    { title: "首页", to: "#" },
    { title: "政策管理", to: "#" },
    { title: "新增政策文件" },
];

const breadcrumbBack = () => {
	// router.back();
}

const menu1 = ref(false);
const entity = ref({
    name: '',
    code: '',
    dept: '',
    bizType: [],
    pidsName: '',
    ctime: null,
    files: '',
    note: ''
});
const valid = ref(false);
const file = ref(null);
const fileShow = ref(true);
const docxId = ref(null);
const Mfile = ref(null);
const form = ref(null);


const displayDate = computed({
    get: () => {
        const formatted = date(entity.value.ctime, 'yyyy-MM-dd');
        return formatted == '无' ? '' : formatted;
    },
    set: (val) => {
        entity.value.ctime = val;
    }
});

// 重置表单数据
const resetForm = () => {
    docxId.value = "";
    entity.value = {
        name: '',
        code: '',
        dept: '',
        bizType: [],
        pidsName: '',
        ctime: null,
        files: '',
        note: ''
    };

    // 重置表单验证状态
    if (form.value) {
        form.value.resetValidation();
    }
};

// 初始化页面状态
const initPage = () => {
    if (route.query.docxEid) {
        // 编辑模式
        docxId.value = route.query.docxEid;
        edit();
        fileShow.value = false;
    } else {
        // 新增模式
        fileShow.value = true;
    }
};

const submitData = async () => {
    const result = await form.value.validate();
    if (result.valid) {
        let formData = new FormData();
        let arr = ["残疾人证", "教育", "康复", "就业", "培训", "保障", "维权", "文体", "无障碍", "其他"];
        let bizName = [];
        entity.value.bizType?.forEach((v) => {
            bizName.push(arr[v]);
        });
        entity.value.areaCode = user.areacode;
        entity.value.areaLeve = user.areacode.length;
        entity.value.btime = entity.value.ctime;
        entity.value.etime = "9999-12-31";
        entity.value.areaName = "无";
        entity.value.state = "1";
        entity.value.stateNote = "生效";
        entity.value.operator = user.username;
        entity.value.bizName = bizName.join();
        entity.value.bizType = entity.value.bizType.join();
        entity.value.pids ??= "0";
        formData.append("docx", new Blob([JSON.stringify(entity.value)], { type: "application/json" }));
        formData.append("file", file.value);
        if (file.value?.size / 1024 / 1024 > 30) {
            proxy.$vtk.message.toast("上传文件大小不能超过30MB!", { color: 'error' })
            return false;
        }
        // 限制格式.pdf
        if (file.value && file.value?.type != "application/pdf") {
            proxy.$vtk.message.toast("请上传PDF文件!", { color: 'error' })
            return false;
        }

        proxy.$vtk.message.loading.show();
        try {
            const res = await setDocxSave(proxy, formData);
            proxy.$vtk.message.loading.hide();

            if (res && res.meta && res.meta.success) {
                proxy.$vtk.message.toast("保存成功！", { color: 'success' })
                router.push({ path: "/fwzx/docx" });
            } else {
                proxy.$vtk.message.toast(res?.meta?.message || "保存失败！", { color: 'error' })
            }
        } catch (error) {
            proxy.$vtk.message.loading.hide();
            proxy.$vtk.message.toast("保存失败！", { color: 'error' })
        }
    }
};

const edit = async () => {
    proxy.$vtk.message.loading.show();
    try {
        const res = await getDocxDetail(proxy, { id: docxId.value });
        proxy.$vtk.message.loading.hide();

        if (res && res.meta && res.meta.success) {
            // 设置表单数据
            entity.value = res.data.docx;
            entity.value.bizType = res.data.docx.bizType.split(",");

            // 处理依据文件
            let pids = [];
            let pidsName = [];
            if (res.data.pids?.length > 0) {
                res.data.pids.forEach((p) => {
                    pids.push(p.id);
                    pidsName.push(p.name);
                });
                entity.value.pids = pids.join();
                entity.value.pidsName = pidsName.join().replace(/,/g, "\n");
            }

            // 格式化日期为 YYYY-MM-DD
            entity.value.ctime = entity.value.ctime.slice(0, 10);
        }
    } catch (error) {
        proxy.$vtk.message.loading.hide();
        proxy.$vtk.message.toast("加载详情失败！", { color: 'error' })
    }
};


// 监听路由变化
watch(
    () => route.query.docxEid,
    (newDocxEid, oldDocxEid) => {
        // 当路由参数变化时
        if (newDocxEid !== oldDocxEid) {
            resetForm();
            initPage();
        }
    }
);

onMounted(() => {
    resetForm();
    initPage();
});

</script>
<!-- 表单可设置top 、left 或者不设置就居中 -->
<template>
    <div>
        <VtkBreadcrumb :items="breadcrumbItems" class="pt-0" @back="breadcrumbBack" />
        <v-form ref="form" v-model="valid" validate-on="submit">
            <v-card elevation="0" class="no-shadow">
                <v-card-text class="pt-12" style="position: relative">
                    <vtk-form-item label="文件名称：" must left help="文件名称请按照文件的红头填写，去掉前面发文单位，从“关于”或“转发”开始！">
                        <v-text-field v-model="entity.name" :rules="[(v) => !!v || '文件名称不能为空!']" placeholder="文件名称"
                            clearable density="compact" variant="outlined"></v-text-field>
                    </vtk-form-item>
                    <vtk-form-item label="发文字号：" must left help="文件字号请从文件正文字号部分复制，保持和原文件一致！">
                        <v-text-field v-model="entity.code" :rules="[(v) => !!v || '发文字号不能为空!']" placeholder="发文字号"
                            clearable density="compact" variant="outlined"></v-text-field>
                    </vtk-form-item>
                    <vtk-form-item label="发文机关：" must left help="发文机关请从文件的红头获取，每个发文机关独占一行，以方便查看！">
                        <v-textarea v-model="entity.dept" :rules="[(v) => !!v || '发文机关不能为空!']" placeholder="发文机关"
                            variant="outlined" rows="3"></v-textarea>
                    </vtk-form-item>
                    <vtk-form-item label="业务类型：" must left Tstyle="vertical-align: top;margin-top:5px"
                        help="业务类型是根据文件内容初步判断划分业务，方便后续的标签检索！">
                        <vtk-select v-model="entity.bizType" placeholder="业务类型"
                            list="0:残疾人证/1:教育/2:康复/3:就业/4:培训/5:保障/6:维权/7:文体/8:无障碍/9:其他 "
                            :rules="[(v) => Array.isArray(v) && v.length > 0 || '业务类型不能为空!']"  variant="outlined" density="compact"
                            :multi="true"></vtk-select>
                    </vtk-form-item>

                    <vtk-form-item label="发布日期：" must left help="发布日期请根据文件发布的实际时间填写！">
                        <v-menu v-model="menu1" :close-on-content-click="false" location="bottom">
                            <template v-slot:activator="{ props }">
                                <v-text-field v-model="displayDate" :rules="[(v) => !!v || '发布日期不能为空!']"
                                    append-inner-icon="mdi-calendar" placeholder="发布日期" density="compact"
                                    variant="outlined" readonly v-bind="props"></v-text-field>
                            </template>
                            <v-date-picker v-model="entity.ctime" locale="zhHans" hide-header
                                @update:model-value="menu1 = false"></v-date-picker>
                        </v-menu>
                    </vtk-form-item>
                    <vtk-form-item label="发文简介：" must left help="发文简介要求用简洁的预言概述整个文件的主要内容，方便后续查阅！">
                        <v-textarea v-model="entity.note" :rules="[(v) => !!v || '发文简介不能为空!']" placeholder="发文简介"
                            density="compact" variant="outlined" rows="3"></v-textarea>
                    </vtk-form-item>

                    <vtk-form-item v-if="fileShow" label="原始文件：" must left help="原始文件为政策文件的PDF电子档，上传后可以再多个设备中直接打开！">
                        <v-file-input v-model="file" accept=".pdf" :rules="[(v) => !!v || '政策文件不能为空!']" prepend-icon=""
                            append-inner-icon="mdi-link-variant" placeholder="请选择政策文件附件..." density="compact"
                            variant="outlined">
                            <template v-if="docxId && fileShow" v-slot:append>
                                <v-btn @click="fileShow = !fileShow" color="blue" icon="mdi-close-circle" size="small"
                                    variant="flat"></v-btn>
                            </template>
                        </v-file-input>
                    </vtk-form-item>

                    <vtk-form-item v-else label="原始文件：" must left help="原始文件为政策文件的PDF电子档，上传后可以再多个设备中直接打开！">
                        <v-alert variant="tonal" border="start" color="blue" class="py-2">
                            <div class="d-flex justify-space-between align-center">
                                <a :href="`${entity.files}?stoken=${proxy.$vtk.storage.get('_mis_acis_token')}`" target="_blank"
                                    class="text-decoration-none">
                                    {{ entity.name }}
                                </a>
                                <v-btn @click="fileShow = !fileShow" color="blue" icon="mdi-close-circle" size="small"
                                    variant="text"></v-btn>
                            </div>
                        </v-alert>
                    </vtk-form-item>
                </v-card-text>
                <div class="pt-0 pb-6" style="margin-left: 140px;">
                    <v-btn @click="submitData" elevation="0" color="primary"><v-icon
                            class="mr-1">mdi-checkbox-marked-circle-outline</v-icon>提交</v-btn>
                    <v-btn @click="$router.go(-1)" elevation="0"><v-icon
                            class="mr-1">mdi-undo-variant</v-icon>返回</v-btn>
                </div>
            </v-card>
        </v-form>
    </div>
</template>

<style scoped></style>