<template>
  <el-dialog v-dialogDrag :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center :close-on-click-modal="false">
    <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" />
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSave">{{ $t('global.confirm') }}</el-button>
      <el-button @click="handleClose">{{ $t('global.cancel') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie';
import ConstConfig from '@/scripts/ConstConfig';
import { postSimulationStats } from '@/api/simulation';
import { getDimUserList } from '@/api/management/user';
import { getPublishMapList } from '@/api/jmap/map';

export default {
    name: 'UsersTrainingAdd',
    props: {
        type: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            formModel: {
                mapId: '',
                prdType: '',
                userId: '',
                userName: '',
                duration: ''
            },
            LessonList: [],
            UserList: [],
            UserLoading: false
        };
    },
    computed: {
        prdTypeList() {
            const productTypeList = ConstConfig.ConstSelect.prdType;
            return Cookies.get('user_lang') == 'en'
                ? productTypeList.map(elem => { return { value: elem.value, label: elem.enlabel }; })
                : productTypeList.map(elem => { return { value: elem.value, label: elem.label }; });
        },
        form() {
            const form = {
                labelWidth: '120px',
                items: [
                    { prop: 'mapId', label: this.$t('system.mapName'), type: 'select', required: true, options: this.LessonList, placeholder: this.$t('rules.mapInput') },
                    { prop: 'prdType', label: this.$t('system.productType'), type: 'select', required: true, options: this.prdTypeList, placeholder: this.$t('rules.productTypeInput') },
                    { prop: 'userName', label: this.$t('system.userName'), type: 'complete', required: false, querySearchAsync: this.querySearchAsync, handleSelect: this.prdSelect, placeholder: this.$t('system.pleaseInputNames') },
                    { prop: 'duration', label: this.$t('system.trainingUseTime'), type: 'text', rightWidth: true, required: true, message: 's' }
                ]
            };
            return form;
        },
        rules() {
            const crules = {
                mapId: [
                    { required: true, message: this.$t('rules.mapInput'), trigger: 'change' }
                ],
                userName: [
                    { required: true, message: this.$t('rules.chooseUser'), trigger: 'change' }
                ],
                prdType: [
                    { required: true, message: this.$t('rules.productInput'), trigger: 'change' }
                ],
                duration: [
                    { required: true, message: this.$t('rules.timeInput'), trigger: 'blur' }
                ]
            };
            return crules;
        },
        title() {
            return this.$t('system.createSimulationTitle');
        }
    },
    mounted() {
        this.initLoadPage();
    },
    methods: {
        initLoadPage() {
            // 加载发布课程列表
            this.LessonList.length = 0;
            this.UserList.length = 0;
            const param = {
                pageNum: 1,
                pageSize: 10
            };
            getPublishMapList(param).then(response => {
                const data = response.data.list;
                if (data && data.length) {
                    data.forEach(elem => {
                        this.LessonList.push({ value: elem.id, label: elem.name });
                    });
                }
            });
        },
        // 搜索查询input
        async querySearchAsync(queryString, cb) {
            // 根据queryString 查询用户 并显示
            const results = [];
            if (queryString) {
                try {
                    const params = {
                        fuzzyParam: queryString
                    };
                    const res = await getDimUserList(params);
                    const list = res.data;
                    list.forEach(item => {
                        const value = {
                            id: item.id,
                            value: `${item.nickname}(${item.name})${item.mobile}`
                        };
                        results.push(value);
                    });
                    cb(results);
                } catch (error) {
                    console.error(error);
                    cb(results);
                }
            } else {
                cb(results);
            }
        },
        prdSelect(item) {
            this.formModel.userId = item.id;
        },
        show(data) {
            this.dialogVisible = true;
        },
        doSave() {
            const self = this;
            this.$refs.dataform.validateForm(() => {
                self.save();
            });
        },
        save() {
            const self = this;
            const params = {
                mapId: this.formModel.mapId,
                prdType: this.formModel.prdType,
                userId: this.formModel.userId,
                duration: parseInt(this.formModel.duration)
            };
            if (params.userId) {
                postSimulationStats(params).then(response => {
                    self.$message.success(this.$t('system.addSuccess'));
                    self.handleClose();
                    self.$emit('reloadTable');
                }).catch(error => {
                    self.$message.error(this.$t('error.addFailed') + error.message);
                });
            } else {
                this.$message.error(this.$t('rules.chooseUser'));
            }
        },
        handleClose(done) {
            this.formModel = {
                mapId: '',
                prdType: '',
                userId: '',
                userName: '',
                duration: ''
            };
            this.$refs.dataform.resetForm();
            this.dialogVisible = false;
        }
    }
};
</script>
