<template>
  <el-dialog v-dialogDrag :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center class="uploadDialog">
    <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" />
    <div class="fileError">{{ message }}</div>
    <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 { postUploadFile, putUploadFile } from '@/api/pdf';
// import { getPublishMapDetailById, getPublishMapVersionById } from '@/api/jmap/map';
// import { dbReadData, dbAddData, dbUpdateData } from '@/utils/indexedDb';
// uploadFile
import { meansUrl } from '@/api/upload';
import { DrawingType } from '@/scripts/ConstDic';

export default {
    name: 'TrainingDetailEdit',
    props: {
        type: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            formModel: {
                upload: '',
                filePath: '',
                fileType: DrawingType.drawing,
                fileName:''
            },
            fileList: [],
            formData: '',
            id: '',
            message:'',
            fileTypeList: [
                {label: '设备图纸', value: DrawingType.drawing},
                {label: '基础设备培训', value: DrawingType.baDeTr},
                {label: '经典案例分析', value: DrawingType.clCaAn},
                {label: '规范学习', value: DrawingType.normStudy}
            ]
            // deviceTypeList: [
            //     { label: '区段', value: 'sectionList', code: 'SECTION' },
            //     { label: '道岔', value: 'switchList', code: 'SWITCH' },
            //     { label: '信号机', value: 'signalList', code: 'SIGNAL' },
            //     { label: '车站', value: 'stationList', code: 'STATION' },
            //     { label: '站台', value: 'stationStandList', code: 'STAND' },
            //     { label: '屏蔽门', value: 'psdList', code: 'PSD' },
            //     { label: '列车', value: 'trainList', code: 'TRAIN' }
            // ],
        };
    },
    computed: {
        action() {
            return `${process.env.VUE_APP_UPLOAD_API}${meansUrl}`;
        },
        form() {
            const form = {
                labelWidth: '120px',
                items: [
                    // { prop: 'mapId', label: '选择线路:', type:'select', options: this.mapList, optionValue:'id', optionLabel:'name', change: true, onChange: this.handleMap },
                    // { prop: 'deviceTypes', label: '选择设备类型:', type:'select', options: this.deviceTypeList, optionValue:'value', optionLabel:'label', change: true, onChange: this.handleDevice },
                    // { prop: 'deviceIds', label: '选择设备:', type:'select', multiple: true, options: this.deviceCodesList, optionValue:'code', optionLabel:'name' },
                    { prop: 'fileName', label: '文件名:', type:'text', show:true, rightWidth:true, required:true },
                    { prop: 'fileType', label: '文件类型', type: 'select', options: this.fileTypeList, optionValue: 'value', optionLabel: 'label'},
                    { prop: 'upload', label: '上传:', type:'uploadPicture', fileList: this.fileList, show: this.type == 'ADD', action: this.action, onChange: this.onChange, onSuccess: this.onSuccess }
                ]
            };
            return form;
        },
        rules() {
            const crules = {
                fileName: [
                    { required: true, message: '文件名不能为空', trigger: 'blur'}
                ],
                fileType: [
                    { required: true, message: '文件类型不能为空', trigger: 'blur' }
                ]
                // upload: [
                //     { required: true, message: '请上传文件', trigger: 'onChange' }
                // ]
            };
            return crules;
        },
        title() {
            if (this.type === 'ADD') {
                return '上传PDF';
            } else {
                return '更新PDF';
            }
        }
    },
    methods: {
        async show(data) {
            this.dialogVisible = true;
            if (this.type != 'ADD') {
                this.id = data.id;
                this.formModel = {
                    upload: '',
                    fileName:data.fileName,
                    fileType: data.fileType,
                    filePath: data.filePath
                };
            } else {
                this.formModel = {
                    upload: '',
                    filePath: '',
                    fileType: DrawingType.drawing,
                    fileName:''
                };
            }
            this.$nextTick(() => {
                this.$refs.dataform.clearFiles();
            });
        },
        // async handleMap(mapId) {
        //     if (mapId) {
        //         if (mapId != this.rowData.mapId) {
        //             this.formModel.deviceIds = [];
        //             this.formModel.deviceTypes = '';
        //         }
        //         return new Promise(async (resolve, reject) => {
        //             const resp = await getPublishMapVersionById(mapId);
        //             const version = resp.data;
        //             dbReadData('mapData', mapId, version, async (mapData, version) =>{
        //                 if (mapData && mapData.version == version) {
        //                     this.graphDataNew = mapData.graphDataNew;
        //                     resolve();
        //                 } else if (mapData) {
        //                     const res = await getPublishMapDetailById(mapId);
        //                     this.graphDataNew = res.data.graphDataNew;
        //                     dbUpdateData('mapData', res.data);
        //                     resolve();
        //                 } else {
        //                     const res = await getPublishMapDetailById(mapId);
        //                     this.graphDataNew = res.data.graphDataNew;
        //                     dbAddData('mapData', res.data);
        //                     resolve();
        //                 }
        //             });
        //         });
        //     } else {
        //         this.formModel.deviceIds = [];
        //         this.formModel.mapId = '';
        //         this.formModel.deviceTypes = '';
        //     }
        // },
        // handleDevice(type) {
        //     if (type) {
        //         if (type != this.rowData.deviceTypes) {
        //             this.formModel.deviceIds = [];
        //         }
        //         this.deviceCodesList = this.graphDataNew[type].map(el => {
        //             return {
        //                 code: el.code,
        //                 name: `${el.name}(${el.code})`
        //             };
        //         });
        //     } else {
        //         this.formModel.deviceIds = [];
        //     }
        // },
        // uploadFile(file) {
        // this.formData.append('file', file.file);
        // },
        onSuccess(res, file) {
            this.formModel.filePath = res.data;
            this.message = '';
        },
        doSave() {
            const self = this;
            this.$refs.dataform.validateForm(() => {
                if (self.type == 'ADD') {
                    if (this.formModel.filePath) {
                        self.create();
                    } else {
                        this.message = '请上传文件';
                        return false;
                    }
                } else {
                    self.update();
                }
            });
        },
        create() {
            const self = this;
            const data = {
                fileType: this.formModel.fileType,
                filePath: this.formModel.filePath,
                fileName:this.formModel.fileName
            };
            postUploadFile(data).then((res) => {
                self.$message.success('上传PDF成功!');
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                console.log(error);
                self.$message.error(`上传PDF失败:${error.message}`);
            });
        },
        update() {
            const self = this;
            const data = {
                id: this.id,
                fileType: this.formModel.fileType,
                fileName:this.formModel.fileName,
                filePath: this.formModel.filePath
            };
            putUploadFile(data).then(() => {
                self.$message.success('更新PDF成功!');
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.$message.error(`更新PDF失败:${error.message}`);
            });
        },
        handleClose() {
            this.message = '';
            this.formModel = {
                upload: '',
                filePath: '',
                fileType: DrawingType.drawing,
                fileName:''
            };
            this.$refs.dataform.resetForm();
            this.dialogVisible = false;
        }
    }
};
</script>

<style lang="scss" scoped>
.uploadDialog{
	/deep/ {
		.el-select--medium{
			width: 300px;
		}
	}
}
.fileError{
    color: red;
    font-size: 13px;
    margin-left: 122px;
    vertical-align: top;
    display: inline-block;
    margin-top: -10px;
}
</style>
