<template>
    <Wraper :hidden="hidden" :refresh="refresh" :onOk="submit">
        <a-form-model layout="vertical" :model="form" :rules="rules" ref="form">
            <a-form-model-item :label="$t('role.roleName')" prop="roleName">
                <a-input v-model="form.roleName" :placeholder="$t('input.placeholder')" />
            </a-form-model-item>
            <a-form-model-item :label="$t('role.roleCode')" prop="roleCode">
                <a-input v-model="form.roleCode" :placeholder="$t('input.placeholder')" />
            </a-form-model-item>
            <a-form-model-item :label="$t('role.roleRemark')" prop="remark">
                <a-input v-model="form.remark" :placeholder="$t('input.placeholder')" />
            </a-form-model-item>

            <a-form-model-item :label="$t('role.menuPermissions')">
                <MenuTree
                    v-model="checkedKeys"
                    :defaultCheckedKeys="defaultCheckedKeys"
                    showMenu
                    ref="menuTree"
                />
            </a-form-model-item>
        </a-form-model>
    </Wraper>
</template>

<script>
import MenuTree from '@/components/menu_tree/index.vue';
import { addRoleApi, getRoleApi, updateRoleApi } from '@/api';
import { WraperMixins } from '@/components/table';

export default {
    mixins: [WraperMixins],
    components: { MenuTree },
    data() {
        return {
            form: {},
            rules: {
                roleName: [{ required: true, message: this.$t('role.roleNameInput') }],
                roleCode: [{ required: true, message: this.$t('role.roleCodeInput') }],
            },
            checkedKeys: [],
            defaultCheckedKeys: [],
        };
    },
    computed: {
        isEdit() {
            return this.type === 'edit';
        },
    },

    mounted() {
        if (this.type) {
            this.getData(this.row.roleId);
        }
    },
    methods: {
        async submit() {
            await this.$refs.form.validate();
            const query = {
                ...this.form,
                authorityList: this.$refs['menuTree'].get().map((i) => ({
                    ...i,
                    nodeId: i.menuId,
                    parentNodeId: i.parentMenuId,
                    nodeType: i.menuType,
                })),
            };
            return this.isEdit ? updateRoleApi(query) : addRoleApi(query);
        },

        async getData(id) {
            const res = await getRoleApi(id);
            this.form = res;
            this.defaultCheckedKeys = res.menuComponentKeys.map((i) => parseInt(i.split('-')[0]));
        },
    },
};
</script>
