<template>
    <div style="padding:10px">
        <q-card inline class="fit shadow-6">
            <!-- <q-card-title>
        <p class="caption">功能管理</p>
        <q-icon slot="right" name="edit" />
      </q-card-title> -->
            <q-card-main style="height:80%">
                <q-table ref="table" color="primary" :data="serverData" :columns="columns" separator="cell" row-key="id"
                         :pagination.sync="serverPagination" @request="request" :loading="loading" :rows-per-page-options="[5,10,20,30,40,50,60,200,500]" :rows-per-page-label="$t('Rows per page')" :no-data-label="$t('No data')">
                    <template slot="top-left" slot-scope="props">
                        <q-input v-model="filter.title"  type="text" prefix="名称：" />&nbsp;&nbsp;
                        <!-- <q-input v-model="filter.name"  type="text" :prefix="$t('Role code') + '：'" />&nbsp;&nbsp; -->
                        <q-btn push dense color="primary" icon="search" @click="search">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
                        <q-btn push dense color="primary" icon="add" @click="addapp">{{$t('Add')}}</q-btn>
                    </template>
                    <template slot="top-right" slot-scope="props">
                        <q-btn flat round dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen" />
                    </template>
                    <template slot="top-selection" slot-scope="props">
                        <q-btn color="negative" flat round delete icon="delete" @click="delRoles" />
                    </template>
                    <q-td slot="body-cell-href" slot-scope="props" :props="props">
                        <span>电脑入口：{{ props.row.href ? props.row.href: '未维护'}}</span><br/>
                        <span>企微入口：{{ props.row.wechatUrl ? props.row.wechatUrl: '未维护' }}</span>
                    </q-td>
                    <q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:100px">
                        <!-- <q-btn small round push glossy dense icon="edit" color="primary" @click="editapp(props.value)"></q-btn>
                        <q-btn small round push glossy dense icon="delete" color="red" @click="delapp(props.value)"></q-btn> -->
                        <q-btn-dropdown color="secondary" label="操作" no-wrap>
                            <q-list link>
                                <q-item v-close-overlay @click.native="editapp(props.value)">
                                    <q-item-main>
                                    <q-item-tile sublabel>修改</q-item-tile>
                                    </q-item-main>
                                </q-item>
                                 <!--<q-item v-close-overlay @click.native="editappVisible(props.value)">
                                    <q-item-main>
                                    <q-item-tile sublabel>修改可见范围</q-item-tile>
                                    </q-item-main>
                                </q-item>-->
                                <q-item v-close-overlay @click.native="delapp(props.value)">
                                    <q-item-main>
                                    <q-item-tile sublabel >删除</q-item-tile>
                                    </q-item-main>
                                </q-item>
                                <q-item v-close-overlay>
                                    <q-item-main>
                                    <q-item-tile sublabel>关闭弹窗</q-item-tile>
                                    </q-item-main>
                                </q-item>
                            </q-list>
                        </q-btn-dropdown>
                    </q-td>
                </q-table>
            </q-card-main>
        </q-card>
        <q-modal v-model="editModal" maximized>
            <q-modal-layout>
                <q-toolbar slot="header">
                    <q-btn flat round dense @click="editModal = false" icon="reply" />
                    <q-toolbar-title>
                        {{$t('Edit')}}
                    </q-toolbar-title>
                </q-toolbar>
                <q-toolbar slot="footer">
                    <q-toolbar-title>
                    </q-toolbar-title>
                    <q-btn round color="red" @click="saveapp"  >{{$t('Save')}}</q-btn>
                    <q-btn round  @click="editModal = false">{{$t('Cancel')}}</q-btn>
                </q-toolbar>

                <div class="layout-padding">
                    <q-field :count="255">
                        <q-input v-model="temp.title" float-label="名称" />
                    </q-field>
                    <q-field>
                        <div class="row no-wrap">
                            <q-select class="col" v-model="temp.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="temp.href" float-label="电脑入口" />
                    </q-field>
                    <q-field :count="255">
                        <q-input v-model="temp.wechatUrl" float-label="企微入口" />
                    </q-field>
                    <q-field :count="64">
                        <q-input v-model="temp.appid" float-label="应用唯一标识" @blur="getsecret()" :disable=appidflag />
                    </q-field>
                    <q-field :count="200">
                        <q-input v-model="temp.secret" float-label="用户的密钥信息" disable />
                    </q-field>
                    <q-field :count="32">
                        <q-input v-model="temp.databasename" float-label="数据库名称" />
                    </q-field>
                    <q-field :count="32">
                        <q-input v-model="temp.databasepassword" float-label="数据库密码" />
                    </q-field>
                    <q-field :count="200">
                        <q-input v-model="temp.databasecon" float-label="数据库连接" />
                    </q-field>
                    <q-field :count="200">
                        <q-select v-model="temp.openmail" float-label="启用待办（启用后会在待办中显示待办信息）" radio :options="openmailOptions"/>
                    </q-field>
                    <q-field :count="200">
                        <q-input v-model="temp.mailtype" float-label="待办标识（待办唯一标识，需要给到对方系统）" />
                    </q-field>
                    <q-field>
                        <q-input v-model="temp.img" float-label="图标路径" disable v-if="subtype=='edit'"/>
                        <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()"
                        ></q-uploader>
                    </q-field>
                    <!-- <q-field :count="200">
                        <q-input v-model="temp.description" type="textarea" :max-height="100" rows="7" :float-label="$t('Role description')" />
                    </q-field> -->
                    <q-select v-model="temp.qyflag" float-label="启用/停用" radio :options="selectOptions"/>
                </div>
            </q-modal-layout>
        </q-modal>
    </div>
</template>

<script>
    import { getPlatformApplicationsPagedList,saveapp,delapp } from "@/service/permission/platformapplications";
    import { getApplicationsGroupList,addApplicationsGroup } from "@/service/permission/platformapplicationsGroup";
    const uploadpath="http://nw.sy-metro.com:6104/uploadfileadmin/manager";
    export default {
        data() {
            return {
                uploadurl: "manager/znzl/file/upload/videoandimgurl?uploadPar=adv&",
                selectOptions:[
                    {
                        label: '启用',
                        value: '1'
                    },
                    {
                        label: '停用',
                        value: '0'
                    },
                ],
                openmailOptions:[
                    {
                        label: '启用',
                        value: '1'
                    },
                    {
                        label: '停用',
                        value: '0'
                    },
                ],
                serverData: [],
                serverPagination: {
                    page: 1,
                    rowsNumber: 0, // specifying this determines pagination is server-side
                    rowsPerPage: 10 // current rows per page being displayed
                },
                columns: [
                    {
                        name: "title",
                        required: true,
                        label: '名称',
                        align: "left",
                        field: "title",
                        sortable: true
                    },
                    {
                        name: "href",
                        required: true,
                        label: '连接',
                        align: "left",
                        field: "href",
                        sortable: true
                    },
                    {
                        name: "openmail",
                        required: true,
                        label: '开启待办',
                        align: "left",
                        field: "openmail",
                        sortable: true,
                        format: function(val, row) {
                            return val == 1 ? '启用' : '停用'
                        }
                    },
                    {
                        name: "mailtype",
                        required: true,
                        label: '待办标识',
                        align: "left",
                        field: "mailtype",
                        sortable: true
                    },
                    {
                        name: "addtime",
                        required: true,
                        label: '添加时间',
                        align: "left",
                        field: "addtime",
                        sortable: true
                    },
                    {
                        name: "id",
                        required: true,
                        label: '操作',
                        align: "left",
                        field: "id",
                        sortable: true
                    },
                ],
                filter: {
                    title: "",
                },
                selected: [],
                loading: false,
                editModal: false,
                temp:{
                    openmail: '0'
                },
                appidflag:true,
                subtype: "add",
                fileCount: 0,
                applicationsGroupOptions: [] // 应用分组下拉选项
            }
        },
        mounted() {
            this.request({
                pagination: this.serverPagination,
                filter: this.filter
            });

            // 获取应用分组选项
            this.getApplicationsGroupOptions();
        },
        methods: {
            async request(props) {
                this.loading = true;
                this.serverPagination = props.pagination;
                let table = this.$refs.table,
                    { page, rowsPerPage, sortBy, descending } = props.pagination;
                let query = {
                    pageNum: page,
                    pageSize: rowsPerPage,
                    sortBy: sortBy,
                    descending: descending,
                    title: this.filter.title
                };
                let dataRes = await getPlatformApplicationsPagedList(query);
                let data = dataRes.data.data;
                this.serverPagination.rowsNumber = data.total;
                this.serverData = data.list;
                setTimeout(() => {
                    this.loading = false;
                }, 500);
            },
            search() {
                this.request({
                    pagination: this.serverPagination,
                    filter: this.filter
                });
            },
            addapp() {
                this.temp = {};
                this.subtype = "add";
                this.editModal = true;
                this.appidflag = false;
            },
            async saveapp() {
                await saveapp(this.temp);
                this.$q.notify({
                    type: "positive",
                    message: this.$t("Saved successfully"),
                    position: "bottom-right"
                });
                this.editModal = false;
                this.search();
            },
            editapp(id) {
                this.subtype = "edit";
                let edit = this.serverData.filter(s => {
                    return s.id === id;
                });
                if (edit && edit.length > 0) {
                    this.temp = JSON.parse(JSON.stringify(edit[0]));
                    this.temp.openmail = this.temp.openmail + ''
                } else {
                    return true;
                }
                this.editModal = true;
                this.appidflag = true;
            },
            editappVisible(id){
            	this.$router.push('/system/sysadv');
            },
            async delapp(id) {
                try {
                    await this.$q.dialog({
                        title: this.$t("Delete"),
                        message: this.$t("Confirm the deletion？"),
                        position: "right",
                        ok: {
                            push: true,
                            label: this.$t("Delete")
                        },
                        cancel: {
                            push: true,
                            color: "negative",
                            label: this.$t("Cancel")
                        }
                    });
                    await delapp({ id: id });
                    this.$q.notify({
                        type: "positive",
                        message: this.$t("Successfully deleted"),
                        position: "bottom-right"
                    });
                    this.search();
                } catch (e) {}
            },
            getsecret(){
                this.temp.secret = window.btoa(this.temp.appid);
            },
            attachmentUploaded(file, xhr) {
      
                let res = JSON.parse(xhr.response).path;
                this.fileCount++;
                if (res != "") {
                    this.$q.notify({
                        message: "上传成功",
                        type: "positive",
                        icon: "done",
                        timeout: 1000,
                        position: "top-right"
                    });
                    this.temp.img = res;
                    console.log(res);
                    if (this.fileCount > 1) {
                    
                        var cNode = document.getElementsByClassName("q-uploader-files")[0];
                        cNode.removeChild(cNode.childNodes[0]);
                    }
                } else {
                    this.$q.notify({
                        message: res.msg,
                        type: "negative",
                        icon: "error_outline",
                        timeout: 3000,
                        position: "top-right"
                    });
                }
            },
            // 获取应用分组选项
            async getApplicationsGroupOptions() {
                try {
                    const response = await getApplicationsGroupList({});
                    this.applicationsGroupOptions = response.data.data.map(group => ({
                        label: group.groupName,
                        value: group.groupCode
                    }));
                } catch (error) {
                    console.error("Failed to fetch applications group options:", error);
                }
            },
            // 点击添加应用分组按钮
            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 }
                    });
                    console.log(name);
                    // `name` contains the input string in this Quasar version
                    if (name) {
                        const groupName = name; // be defensive across versions
                        await addApplicationsGroup({ groupName: groupName });
                        this.$q.notify({ type: 'positive', message: '添加成功', position: 'bottom-right' });
                        // refresh options
                        await this.getApplicationsGroupOptions();
                    }
                } catch (e) {
                    // user cancelled or error
                }
            },
        },
    }
</script>

<style scoped>

</style>