<template>
    <el-dialog :title="operation.title" :visible.sync="dialogShow" width="500px" :before-close="close">
        <el-form ref="form" :model="operateModel" label-width="100px" :rules="rules" size="mini">
            <el-form-item label="皮肤类型:" prop="skinStyle">
                <el-select v-model="operateModel.skinStyle" @change="skinStyleChoose">
                    <el-option v-for="option in skinStyleList" :key="option.code" :label="option.name"
                        :value="option.code">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产品类型:" prop="prdCode">
                <el-select v-model="operateModel.prdCode" @change="prdChange">
                    <el-option v-for="option in productList" :key="option.code" :label="option.name"
                        :value="option.code">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="实训类型:" prop="type">
                <el-select v-model="operateModel.type" @change="typeChange">
                    <el-option v-for="option in trainingTypeLists" :key="option.code" :label="option.name"
                        :value="option.code">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="操作类型:" prop="operateType">
                <el-select v-model="operateModel.operateType" multiple>
                    <el-option v-for="option in trainingTypeMap[operateModel.type]" :key="option.code"
                        :label="option.name" :value="option.code">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="最小用时:" prop="minDuration" v-if="isUpdate">
                <el-input-number v-model="operateModel.minDuration" :min="0" :max="10000"></el-input-number>s
            </el-form-item>
            <el-form-item label="最大用时:" prop="maxDuration" v-if="isUpdate">
                <el-input-number v-model="operateModel.maxDuration" :min="0" :max="10000"></el-input-number>s
            </el-form-item>
            <el-form-item label="实训描述:" prop="remarks" v-if="isUpdate">
                <el-input type="textarea" v-model="operateModel.remarks"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleDeal" :loading="loading">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import { getPublishMapInfo } from '@/api/jmap/map';
    import { addAutoTraining, updateAutoTraining, deleteAutoTraining } from '@/api/jmap/training';
    import { getOperateTrainingList } from '@/api/management/operation';
    import { getCommodityMapProduct } from '@/api/management/mapprd';
    import localStore from 'storejs';

    export default {
        name: 'TrainingAdd',
        props: {
            skinStyleList: {
                type: Array,
                required: true
            },
            trainingTypeList: {
                type: Array,
                required: true
            },
            trainingOperateTypeMap: {
                type: Object,
                required: true
            }
        },
        data() {
            var minDurations = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入标准用时'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        callback();
                    }
                }, 100);
            };
            var maxDurations = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入标准用时'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if (value < this.operateModel.minDuration) {
                            callback(new Error('必须大于最小时间'));
                        } else {
                            callback();
                        }
                    }
                }, 100);
            };

            var checkOperateType = (rule, value, callback) => {
                if (value.length <= 0) {
                    return callback(new Error('请选择实训类型'));
                } else if (this.operation.event == '02' && value.length !== 1) {
                    return callback(new Error('只能选择一个实训类型'));
                } else {
                    callback();
                }
            }

            var checkRemarks = (rule, value, callback) => {
                if (this.operation.event == '02' && !value) {
                    return callback(new Error('请输入实训描述'));
                }
                callback();
            };

            return {
                dialogShow: false,
                productTypesList: [],
                trainTypesList: [],
                productList: [],
                checkList: [],
                operateModel: {
                    name: '',
                    type: '',
                    skinStyle: '',
                    prdCode: '',
                    operateType: [],
                    maxDuration: 0,
                    minDuration: 0,
                    remarks: '',
                },
                loading: false,
                trainingTypeLists: [],
                trainingTypeMap: {},
                operation: {
                    event: '',
                    title: '',
                },
                rules: {
                    skinStyle: [
                        { required: true, message: '请输入地图名称', trigger: 'change' }
                    ],
                    prdCode: [
                        { required: true, message: '请输入产品类型', trigger: 'change' }
                    ],
                    type: [
                        { required: true, message: '请输入实训类型', trigger: 'change' }
                    ],
                    operateType: [
                        { required: true, validator: checkOperateType, trigger: 'change' }
                    ],
                    minDuration: [
                        { required: true, validator: minDurations, trigger: 'blur' }
                    ],
                    maxDuration: [
                        { required: true, validator: maxDurations, trigger: 'blur' }
                    ],
                    // remarks: [
                    //     { required: true, validator: checkRemarks, trigger: 'blur' }
                    // ]
                }
            }
        },
        computed: {
            isUpdate() {
                return this.operation.event == '02';
            }
        },
        methods: {
            show(data) {
                this.operation = {
                    event: data.event,
                    title: data.title
                }
                this.dialogShow = true;
            },
            close() {
                this.dialogShow = false;
                this.loading = false;
            },
            skinStyleChoose(skinStyle) {
                this.operateModel.prdCode = '';
                this.productList = [];
                if (skinStyle) {
                    getCommodityMapProduct(skinStyle).then((response) => {
                        this.productList = response.data;
                        this.productList = this.productList.filter(elem => { return elem.prdType != '03'; })
                    })
                }
            },
            async prdChange(prdCode) {
                this.trainingTypeMap = {};
                this.operateModel.operateType = [];

                let skinStyleObj = this.skinStyleList.find(elem => { return elem.code === this.operateModel.skinStyle }) || {};
                let prdTypeObj = this.productList.find(elem => { return elem.code === prdCode }) || {};
                let res = await getOperateTrainingList({ skinStyle: skinStyleObj.code, productType: prdTypeObj.prdType });
                if (res && res.code == 200) {
                    this.trainingTypeLists = res.data;
                    this.trainingTypeList.forEach(elem => {
                        this.trainingTypeLists.forEach(item => {
                            if (item.id == elem.code) {
                                item.name = elem.name;
                                item.code = elem.code;
                            }

                            this.trainingOperateTypeMap[item.id].forEach(i => {
                                item.children.forEach(v => {
                                    if (i.code == v.id) {
                                        v.name = i.name;
                                        v.code = i.code;
                                    }
                                })
                            })
                        });
                    })

                    this.trainingTypeLists.forEach(item => {
                        item.children.forEach(v => {
                            if (!this.trainingTypeMap[item.id]) {
                                this.trainingTypeMap[item.id] = [];
                            }

                            this.trainingTypeMap[item.id].push({
                                name: v.name,
                                code: v.code,
                            });
                        })
                    });
                }
            },
            typeChange(type) {
                this.operateModel.operateType = [];
                this.trainTypesList = this.trainingOperateTypeMap[type] || []
            },
            // 取消
            handleClose() {
                this.dialogShow = false;
            },
            // 确定
            handleDeal() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        if (this.operation.event == '01') { //add
                            //创建实训
                            let data = {
                                skinStyle: this.operateModel.skinStyle,
                                name: this.operateModel.name,
                                prdCode: this.operateModel.prdCode,
                                trainingType: this.operateModel.type,
                                operateType: this.operateModel.operateType
                            }

                            addAutoTraining(data).then(response => {
                                this.$message.success('自动生成实训成功！');
                                this.$emit('refresh');
                                this.close();
                            }).catch(error => {
                                this.$messageBox('生成实训失败');
                                this.loading = false;
                            });
                        } else if (this.operation.event == '02') { //edit
                            //更新实训
                            let data = {
                                skinStyle: this.operateModel.skinStyle,
                                name: this.operateModel.name,
                                prdCode: this.operateModel.prdCode,
                                trainingType: this.operateModel.type,
                                operateType: this.operateModel.operateType,
                                remarks: this.operateModel.remarks,
                                minDuration: this.operateModel.minDuration,
                                maxDuration: this.operateModel.maxDuration
                            }

                            updateAutoTraining(data).then(response => {
                                this.$message.success('更新自动生成实训成功！');
                                this.$emit('refresh');
                                this.close();
                            }).catch(error => {
                                this.$messageBox('更新自动生成实训失败');
                                this.loading = false;
                            })
                        } else if (this.operation.event == '03') { //delete
                            //删除实训
                            let data = {
                                skinStyle: this.operateModel.skinStyle,
                                name: this.operateModel.name,
                                prdCode: this.operateModel.prdCode,
                                trainingType: `${this.operateModel.type}`,
                                operateType: `${this.operateModel.operateType.join(',')}`,
                            }

                            deleteAutoTraining(data).then(response => {
                                this.$message.success('删除自动生成实训成功！');
                                this.$emit('refresh');
                                this.close();
                            }).catch(error => {
                                this.$messageBox('删除自动生成实训失败');
                                this.loading = false;
                            });
                        }
                    }
                });
            },
        }
    }

</script>
<style scoped>
    .el-checkbox {
        margin-left: 20px;
    }
</style>