<template>
    <Modal
        :class="bem()"
        centered
        :visible.sync="innerVisible"
        :showCloseButton="true"
        :maskClosable="false"
        :showNewClose="true"
        :onCancel="onCancel"
        @update:visible="v => $emit('update:visible', v)"
        :width="width">
        <template v-if="industryOptions && professionOptions && chosenIndustryOptions && chosenProfessionOptions">
            <choose-industry
                v-show="shownType === 'industry'"
                :allOptions="industryOptions"
                :chosenOptions="chosenIndustryOptions"
                @chooseOption="chooseIndustry"
                @closeDialog="closeDialog"
                @showProfessionOptions="showProfessionOptions"/>
            <choose-profession
                v-show="shownType === 'profession'"
                :allOptions="professionOptions"
                :chosenOptions="chosenProfessionOptions"
                @chooseOption="chooseProfession"
                @closeDialog="closeDialog"
                @showIndustryOptions="showIndustryOptions"/>
        </template>
        <loading-mask :loading="loading" :minHeight="272"/>
    </Modal>
</template>

<script>
import { createComponentName, componentMixin } from '../_utils/component';

import Modal from '../Modal';
import ChooseIndustry from './components/choose-industry';
import ChooseProfession from './components/choose-profession';
import LoadingMask from './components/loading-mask';
import request from '../request';

export default {
    name: createComponentName('user-preference'),
    components: {
        Modal,
        ChooseIndustry,
        ChooseProfession,
        LoadingMask,
    },
    mixins: [componentMixin],
    props: {
        // 弹框显示
        visible: {
            type: Boolean,
            default: false
        },
        // 用户session
        user: {
            type: Object,
            default: () => {
                return {};
            }
        },
        onCancel: {
            type: Function,
        },
    },
    data() {
        return {
            industryOptions: null,
            professionOptions: null,
            chosenIndustryOptions: null,
            chosenProfessionOptions: null,
            shownType: 'industry',
            width: '720px',
            innerVisible: false,
            loading: false,
        };
    },
    computed: {
        // innerVisible: {
        //     get() {
        //         return this.visible;
        //     },
        //     set(visible) {
        //         this.$emit('update:visible', visible);
        //     }
        // },
    },
    watch: {
        'visible': {
            handler(visible) {
                if (visible) {
                    this.innerVisible = visible;
                    this.getOptions();
                    this.markHasWarn();
                };
            },
            immediate: true
        }
    },
    methods: {
        async getOptions() {
            this.loading = true;
            const allRequest = request.get('/api/preferences', {
                params: {
                    page_size: 100
                }
            });
            const chosenRequest = request.get(`/api/users/${this.user.id}/preferences`, {
                params: {
                    // user_id: this.user.id,
                    page_size: 100,
                    with_preference: 1
                }
            });
            const [allOptions, chosenOptions] = await Promise.all([allRequest, chosenRequest]);
            this.setIndustryOptions(allOptions.data);
            this.setProfessionOptions(allOptions.data);
            this.setChosenIndustryOptions(chosenOptions.data);
            this.setChosenProfessionOptions(chosenOptions.data);
            this.loading = false;
        },
        async getChosenOptions() {
            const chosenOptions = await request.get(`/api/users/${this.user.id}/preferences`, {
                page_size: 100,
                with_preference: 1
            });
            this.chosenOptions = chosenOptions.data.map(option => ({
                recordId: option.id,
                preference_id: option.preference_id
            }));
        },
        async chooseIndustry(param) {
            // const resMap = {
            //     update: 'updateUserPreferences',
            //     create: 'createUserPreferences',
            //     delete: 'deleteUserPreferences',
            // };

            const paramMap = {
                update: () => {
                    return request.put(`/api/users/${this.user.id}/preferences/${String(param.recordId)}`, {
                        preference_id: param.id,
                        type: 'industry',
                    });
                },
                create: () => {
                    return request.post(`/api/users/${this.user.id}/preferences`, {
                        preference_id: param.id,
                        type: 'industry',
                    });
                },
                delete: () => {
                    return request.delete(`/api/users/${this.user.id}/preferences/${String(param.recordId)}`, {
                        type: 'industry',
                    });
                }
            };

            await paramMap[param.type]();
            if (param.chosen) this.shownType = 'profession';
            this.getOptions();
        },
        async chooseProfession(param) {
            await request.post(`/api/users/${this.user.id}/preferences/batch`, {
                ...param
            });
            this.closeDialog();
            this.$emit('success');
        },
        setIndustryOptions(allOptions) {
            this.industryOptions = allOptions.filter(option => option.type === 'industry').concat({ name: '其他', id: 0 });
        },
        setProfessionOptions(allOptions) {
            this.professionOptions = allOptions.filter(option => option.type === 'profession').concat({ name: '其他', id: 0 });
        },
        setChosenIndustryOptions(chosenOptions) {
            const options = chosenOptions.filter(option => option.type === 'industry');

            this.chosenIndustryOptions = options.map(option => ({
                recordId: option.id,
                preference_id: option.preference_id
            }));
        },
        setChosenProfessionOptions(chosenOptions) {
            const options = chosenOptions.filter(option => option.type === 'profession');

            this.chosenProfessionOptions = options.map(option => ({
                recordId: option.id,
                preference_id: option.preference_id
            }));
        },
        showProfessionOptions() {
            this.shownType = 'profession';
        },
        showIndustryOptions() {
            this.shownType = 'industry';
        },
        closeDialog() {
            this.innerVisible = false;
        },
        markHasWarn() {
            if (!localStorage.getItem('has-warn-preference')) {
                localStorage.setItem('has-warn-preference', 'true');
            };
        }
    }
};
</script>

<style lang="less" scoped>
@import '../_styles/base.less';

.@{user-preference} {
    & /deep/ .gd-modal {
        overflow: hidden;
    }
    & /deep/ .gd-modal__body {
        min-height: 200px;
    }
    & /deep/ .gd-modal__close {
        font-size: 20px;
    }
    & /deep/ .gd-modal__body::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 136px;
        height: 136px;
        background: url('./assets/background_top.png') no-repeat;
        background-size: contain;
    }
    & /deep/ .gd-modal__body::after {
        content: '';
        position: absolute;
        bottom: -32px;
        right: 0;
        width: 100px;
        height: 100px;
        background: url('./assets/background_bottom.png') no-repeat;
        background-size: contain;
    }
}
</style>
