<template>
    <q-modal v-model="visible" maximized>
        <q-modal-layout>
            <q-toolbar slot="header">
                <q-btn flat round dense @click="close" icon="reply" />
                <q-toolbar-title>
                    编辑应用
                </q-toolbar-title>
            </q-toolbar>
            <q-toolbar slot="footer">
                <q-toolbar-title></q-toolbar-title>
                <q-btn round color="red" @click="onSave">保存</q-btn>
                <q-btn round @click="close">取消</q-btn>
            </q-toolbar>

            <div class="layout-padding edit-app-container">
                <!-- 基本信息 -->
                <q-card class="q-mb-md q-pa-md">
                    <q-card-section>
                        <div class="text-weight-bold q-mb-sm">基本信息</div>
                        <q-field :count="255">
                            <q-input v-model="localTemp.title" float-label="名称" />
                        </q-field>
                        <div class="row">
                            <div class="col-6 q-pr-sm">
                                <q-field :count="64">
                                    <q-input v-model="localTemp.appid" float-label="应用唯一标识" @blur="getsecret" :disable="appidflag" />
                                </q-field>
                            </div>
                            <div class="col-6 q-pl-sm">
                                <q-field :count="200">
                                    <q-input v-model="localTemp.secret" float-label="用户的密钥信息" disable />
                                </q-field>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-6 q-pr-sm">
                                <q-field :count="200">
                                    <q-select v-model="localTemp.openmail" float-label="启用待办" radio :options="openmailOptions"/>
                                </q-field>
                            </div>
                            <div class="col-6 q-pr-sm">
                                <q-field :count="200">
                                    <q-input v-model="localTemp.mailtype" float-label="待办标识" />
                                </q-field>
                            </div>
                        </div>
                        <q-field>
                            <div v-if="localTemp.img" class="image-preview-wrapper">
                                <img :src="localTemp.img" style="width:80px; height:80px; border-radius:6px; border:1px solid #eee; object-fit:cover;" @error="onImgError" @load="onImgLoad" />
                                <div class="q-mt-sm">
                                    <q-btn dense flat color="negative" icon="delete" label="删除" @click="removeImage" />
                                    <q-btn dense flat color="primary" icon="file_upload" label="重新上传" @click="openUploader" />
                                </div>
                                <!-- hidden uploader used for re-upload -->
                                <q-uploader ref="attachmentUploaderHidden"
                                    style="display:none"
                                    name="file"
                                    @uploaded="attachmentUploaded"
                                    :headers="{'Accept': 'application/json;charset=utf-8'}"
                                    :url="uploadurl"
                                    accept="image/*"
                                    :multiple="false"
                                    @add="$refs['attachmentUploaderHidden'].upload()"
                                ></q-uploader>
                            </div>
                            <div v-else>
                                <q-uploader
                                    float-label="上传图标"
                                    ref="attachmentUploader"
                                    name="file"
                                    @uploaded="attachmentUploaded"
                                    :headers="{'Accept': 'application/json;charset=utf-8'}"
                                    :url="uploadurl"
                                    auto-expand
                                    clearable
                                    hide-upload-button
                                    @add="$refs['attachmentUploader'].upload()"
                                    accept="image/*"
                                    :multiple="false"
                                ></q-uploader>
                            </div>
                        </q-field>
                    </q-card-section>
                </q-card>

                <!-- PC 信息 -->
                <q-card class="q-mb-md q-pa-md">
                    <q-card-section>
                        <div class="text-weight-bold q-mb-sm">PC 信息</div>
                        <q-field :count="255">
                            <q-input v-model="localTemp.href" float-label="电脑入口" />
                        </q-field>
                        <q-field>
                            <q-select v-model="localTemp.qyflag" float-label="启用/停用" radio :options="selectOptions"/>
                        </q-field>
                    </q-card-section>
                </q-card>

                <!-- App 信息 -->
                <q-card class="q-pa-md">
                    <q-card-section>
                        <div class="text-weight-bold q-mb-sm">App 信息</div>
                        <q-field>
                            <div class="row no-wrap">
                                <q-select class="col" v-model="localTemp.groupCode" float-label="应用分组" radio :options="applicationsGroupOptions"/>
                                <q-btn color="negative" flat round dense icon="add" @click="openAddApplicationsGroup" />
                            </div>
                        </q-field>
                        <q-field :count="255">
                            <q-input v-model="localTemp.wechatUrl" float-label="企微入口" />
                        </q-field>
                        <q-field :count="200">
                            <q-select v-model="localTemp.appEnable" float-label="应用启用/停用" radio :options="selectOptions"/>
                        </q-field>
                    </q-card-section>
                </q-card>
            </div>
        </q-modal-layout>
    </q-modal>
</template>

<script>
import { saveapp } from "@/service/permission/platformapplications";
import { getApplicationsGroupList, addApplicationsGroup } from "@/service/permission/platformapplicationsGroup";
export default {
    name: "EditApplication",
    props: {
        value: { type: Boolean, default: false },
        temp: { type: Object, default: () => ({}) },
        subtype: { type: String, default: "add" },
        uploadurl: { type: String, default: "" },
        selectOptions: { type: Array, default: () => [] },
        openmailOptions: { type: Array, default: () => [] },
        appidflag: { type: Boolean, default: true }
    },
    data() {
        return {
            visible: this.value,
            localTemp: JSON.parse(JSON.stringify(this.temp || {})),
            fileCount: 0
            ,applicationsGroupOptions: []
            ,imageLoadError: false
        }
    },
    watch: {
        value(v) {
            this.visible = v;
            if (v) {
                this.localTemp = JSON.parse(JSON.stringify(this.temp || {}));
                this.fetchApplicationsGroupOptions();
                if (this.localTemp.appEnable === undefined || this.localTemp.appEnable === null) {
                    this.localTemp.appEnable = '0';
                }
                    if (this.localTemp.img === undefined) {
                        this.$set(this.localTemp, 'img', '');
                    }
            }
        },
        visible(v) {
            this.$emit('input', v);
        },
        temp(n) {
            if (this.visible) {
                this.localTemp = JSON.parse(JSON.stringify(n || {}));
                if (this.localTemp.appEnable === undefined || this.localTemp.appEnable === null) {
                    this.localTemp.appEnable = '0';
                }
                if (this.localTemp.img === undefined) {
                    this.$set(this.localTemp, 'img', '');
                }
            }
        }
    },
    methods: {
        close() {
            this.visible = false;
        },
        async onSave() {
            try {
                await saveapp(JSON.parse(JSON.stringify(this.localTemp)));
                this.$q.notify({
                    type: "positive",
                    message: "保存成功",
                    position: "bottom-right"
                });
                this.$emit('saved');
                this.close();
            } catch (e) {
                this.$q.notify({
                    type: "negative",
                    message: "保存失败",
                    position: "bottom-right"
                });
            }
        },
        getsecret() {
            this.localTemp.secret = window.btoa(this.localTemp.appid || '');
        },
        onImgError() {
            this.imageLoadError = true;
        },
        onImgLoad() {
            this.imageLoadError = false;
        },
        attachmentUploaded(file, xhr) {
            let parsed;
            try {
                parsed = JSON.parse(xhr.response);
            } catch (e) {
                parsed = null;
            }
            const res = parsed ? parsed.path : null;
            if (res && res !== "") {
                this.$q.notify({
                    message: "上传成功",
                    type: "positive",
                    icon: "done",
                    timeout: 1000,
                    position: "top-right"
                });
                // 使用 $set 保证 Vue2 对新增属性的响应式
                try {
                    this.$set(this.localTemp, 'img', res);
                } catch (e) {
                    this.localTemp.img = res;
                }
                // 清理 uploader DOM 列表，兼容 Quasar 0.15
                try {
                    var cNode = document.getElementsByClassName("q-uploader-files")[0];
                    if (cNode && cNode.childNodes.length > 0) {
                        cNode.removeChild(cNode.childNodes[0]);
                    }
                } catch (e) {}
            } else {
                this.$q.notify({
                    message: (parsed && parsed.msg) ? parsed.msg : "上传失败",
                    type: "negative",
                    icon: "error_outline",
                    timeout: 3000,
                    position: "top-right"
                });
            }
        }
        ,
        async fetchApplicationsGroupOptions() {
            try {
                const response = await getApplicationsGroupList({});
                this.applicationsGroupOptions = response.data.data.map(group => ({
                    label: group.groupName,
                    value: group.groupCode
                }));
            } catch (err) {
                console.error("fetchApplicationsGroupOptions error", err);
            }
        },
        async openAddApplicationsGroup() {
            try {
                const name = await this.$q.dialog({
                    title: '添加应用分组',
                    prompt: {
                        model: '',
                        type: 'text',
                        isValid: val => val && val.trim().length > 0
                    },
                    ok: { label: '添加', push: true },
                    cancel: { label: '取消', push: true }
                });
                if (name) {
                    const groupName = name;
                    await addApplicationsGroup({ groupName: groupName });
                    this.$q.notify({ type: 'positive', message: '添加成功', position: 'bottom-right' });
                    await this.fetchApplicationsGroupOptions();
                }
            } catch (e) {
                // cancelled or error
            }
        },
        removeImage() {
            try {
                this.$set(this.localTemp, 'img', '');
            } catch (e) {
                this.localTemp.img = '';
            }
            try {
                var cNode = document.getElementsByClassName("q-uploader-files")[0];
                if (cNode) {
                    while (cNode.firstChild) cNode.removeChild(cNode.firstChild);
                }
            } catch (e) {}
        },
        openUploader() {
            const ref = this.$refs.attachmentUploaderHidden || this.$refs.attachmentUploader;
            if (ref && ref.$el) {
                const input = ref.$el.querySelector('input[type="file"]');
                if (input) input.click();
            }
        }
    }
}
</script>

<style scoped>
/* 美化与响应式布局 */
.edit-app-container {
	padding: 12px 8px;
	max-width: 1100px;
	margin: 0 auto;
}
.edit-app-container .q-card {
	border-radius: 8px;
	/* subtle shadow if not already present in theme */
	box-shadow: 0 6px 18px rgba(28,28,28,0.06);
}
.edit-app-container .q-card-section {
	padding: 16px !important;
}
.edit-app-container .text-weight-bold {
	font-size: 16px;
	color: #e31313;
	margin-bottom: 8px;
}
.edit-app-container .row.q-col-gutter-md {
	margin-bottom: 8px;
}
.edit-app-container .q-field {
	margin-bottom: 6px;
}
.edit-app-container .q-input__control input,
.edit-app-container .q-select__control {
	font-size: 14px;
}
/* make two columns collapse into one on small screens */
@media (max-width: 720px) {
	.edit-app-container .col-6 {
		width: 100% !important;
		flex: 0 0 100% !important;
	}
	.edit-app-container .q-card {
		margin-bottom: 12px;
	}
}
</style>


