<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center>
            <data-form ref="dataform" :form="form" :formModel="formModel" :rules="rules"></data-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="doSave">确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </span>
        </el-dialog>
        <add-training ref="addTraining" @selectTrain="selectTrain"></add-training>
    </div>
</template>

<script>
    import { create, checkDicDetailCodeExist, getData } from '@/api/management/dictionaryDetail'
    import { addUserTraining } from '@/api/jmap/training';
    import { validateCharCode } from '@/utils/validate';
    import { getPublishLessonList } from '@/api/jmap/lesson';
    import { getDimUserList } from '@/api/management/user';
    import AddTraining from './addTraining';

    export default {
        name: 'UsersTrainingAdd',
        props: {
            type: {
                type: String,
                required: true
            },
        },
        components: {
            AddTraining,
        },
        data() {
            return {
                dialogVisible: false,
                formModel: {
                    lessonId: '',
                    trainingId: '',
                    trainingName: '',
                    userId: '',
                    userName: '',
                    duration: '',
                },
                LessonList: [],
                UserList: [],
                UserLoading: false,
            }
        },
        computed: {
            form() {
                let isAdd = this.type === 'ADD'
                let form = {
                    labelWidth: '100px',
                    items: [
                        { prop: 'lessonId', label: '课程名称', type: 'select', required: true, options: this.LessonList, },
                        { prop: 'trainingName', label: '实训名称', type: 'text', required: true, rightWidth: true, disabled: true, buttontip: '选择实训', buttonClick: this.buttonClick, placeholder: '请选择实训' },
                        { prop: 'userName', label: '用户名称', type: 'complete', required: false, placeholder: '', querySearchAsync: this.querySearchAsync, handleSelect: this.prdSelect, placeholder: '请输入昵称/名字/手机号' },
                        { prop: 'duration', label: '实训时长', type: 'text', required: true, rightWidth: true, message: 's' },
                    ]
                }
                return form
            },
            rules() {
                let crules = {
                    lessonId: [
                        { required: true, message: '请输入教学名称', trigger: 'change' },
                    ],
                    trainingName: [
                        { required: true, message: '请选择实训', trigger: 'change' },
                    ],
                    userName: [
                        { required: true, message: '请输入用户名称', trigger: 'change' },
                    ],
                    duration: [
                        { required: true, message: '请输入时长', trigger: 'blur' },
                    ],
                }
                return crules
            },
            title() {
                return '创建用户实训'
            }
        },
        mounted() {
            this.InitLoadPage();
        },
        methods: {
            InitLoadPage() {
                //加载发布课程列表
                this.LessonList.length = 0;
                this.UserList.length = 0;
                getPublishLessonList().then(response => {
                    let data = response.data;
                    if (data && data.length) {
                        data.forEach(elem => {
                            this.LessonList.push({ value: elem.id, label: elem.name });
                        })
                    }
                });
            },
            // 搜索查询input
            async querySearchAsync(queryString, cb) {
                // 根据queryString 查询用户 并显示
                let results = [];
                if (queryString) {
                    try {
                        let params = {
                            fuzzyParam: queryString,
                        };
                        let res = await getDimUserList(params);
                        let list = res.data;
                        list.forEach(item => {
                            let value = {
                                id: item.id,
                                value: `${item.nickname}(${item.name})${item.mobile}`
                            }
                            results.push(value);
                        })
                        cb(results);
                    } catch (error) {
                        console.error(error, '查询用户list');
                        cb(results);
                    }
                } else {
                    cb(results);
                }
            },
            prdSelect(item) {
                this.formModel.userId = item.id;
            },
            selectTrain(data) {
                this.formModel.trainingId = data.id;
                this.formModel.trainingName = data.name;
            },
            buttonClick() {
                if (this.formModel.lessonId) {
                    this.$refs.addTraining.show(this.formModel.lessonId);
                } else {
                    this.$message.error('请先选择课程名称')
                }
            },
            show(data) {
                this.dialogVisible = true
                // this.formModel = {
                //     lessonId: '',
                //     trainingId: '',
                //     trainingName: '',
                //     userId: '',
                //     userName: '',
                //     duration: '',
                // };
            },
            doSave() {
                let self = this
                this.$refs.dataform.validateForm(() => {
                    self.save()
                })
            },
            save() {
                let self = this
                if (this.formModel.userId) {
                    addUserTraining(this.formModel).then(response => {
                        self.$message.success('创建成功！')
                        self.handleClose()
                        self.$emit('reloadTable')
                    }).catch(error => {
                        self.$message.error('创建失败！' + error.message)
                    })
                } else {
                    self.$message.error('请选择用户')
                }
            },
            handleClose(done) {
                this.formModel = {
                    lessonId: '',
                    trainingId: '',
                    trainingName: '',
                    userId: '',
                    userName: '',
                    duration: '',
                }
                this.dialogVisible = false
            }
        }
    }
</script>