<template>
    <div>
        <basic-layout>
            <template slot="header">
                <span class="i-layout-header-trigger i-layout-header-trigger-min">
                    <Dropdown :trigger="isMobile ? 'click' : 'hover'"
                        class="i-layout-header-user"
                        :class="{ 'i-layout-header-user-mobile': isMobile }"
                        @on-click="factorySelected">
                        <Icon type="md-home" />
                        <span class="i-layout-header-user-name"
                            v-if="!isMobile&&data.factory">{{ data.factory.displayName }}</span>
                        <DropdownMenu slot="list">
                            <DropdownItem v-for="item in factories"
                                :key="item.id"
                                :name="item.id">
                                <span>{{ item.displayName }}</span>
                            </DropdownItem>
                        </DropdownMenu>
                    </Dropdown>
                </span>
            </template>
        </basic-layout>
    </div>
</template>
<script>
    import { modelApi, basicLayout, util } from '../../src';
    import userApi from '../api/user';
    import { mapState, mapActions } from 'vuex';

    export default {
        name: 'layout',
        components: {
            basicLayout
        },
        data() {
            return {
                factories: []
            };
        },
        computed: {
            ...mapState('admin/user', ['data']),
            ...mapState('admin/layout', ['isMobile'])
        },
        async created() {
            let res = await modelApi.query('Factory', { is_disabled: false });
            this.factories = res.data;
        },
        methods: {
            ...mapActions('admin/user', ['setData']),
            async factorySelected(id) {
                if (this.data.factory.id != id) {
                    let res = await userApi.setCurrentFactory(id);

                    util.cookies.set('token', res.token);
                    this.setData(res.data);
                }
            }
        }
    };
</script>
