<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" />
    <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';

export default {
    name: 'TrainingDetailEdit',
    props: {
        type: {
            type: String,
            required: true
        },
        mapList:{
            type: Array,
            required: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            formModel: {
                // cityCode: '',
                mapId: '',
                deviceTypes: '',
                deviceIds: [],
                upload: '',
                filePath: '',
                fileType: 'DRAWING'
            },
            rowData: null,
            graphDataNew: null,
            fileList: [],
            formData: '',
            id: '',
            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' }
            ],
            deviceCodesList: []
        };
    },
    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: 'upload', label: '上传:', type:'uploadPicture', show: this.type == 'ADD', action: this.action, fileList: this.fileList, onChange: this.onChange, onSuccess: this.onSuccess }
                ]
            };
            return form;
        },
        rules() {
            const crules = {
                mapId: [
                    { required: true, message: '请选择线路', trigger: 'change' }
                ],
                deviceTypes: [
                    { required: true, message: '请选择设备类型', trigger: 'change' }
                ],
                deviceIds: [
                    { required: true, message: '请选择设备', trigger: 'change' }
                ]
            };
            return crules;
        },
        title() {
            if (this.type === 'ADD') {
                return '上传PDF';
            } else {
                return '更新文章';
            }
        }
    },
    methods: {
        async show(data) {
            this.dialogVisible = true;
            if (this.type != 'ADD') {
                const obj = this.deviceTypeList.find(el => el.code == data.deviceTypes[0]);
                this.id = data.id;
                this.rowData = data;
                this.rowData.deviceTypes = obj ? obj.value : '';
                this.formModel = {
                    mapId: data.mapId,
                    deviceTypes: obj ? obj.value : '',
                    deviceIds: data.deviceIds,
                    upload: '',
                    filePath: data.filePath
                };
                await this.handleMap(data.mapId);
                obj && await this.handleDevice(obj.value);
            } else {
                this.rowData = {};
                this.formModel = {
                    mapId: '',
                    deviceTypes: '',
                    deviceIds: [],
                    upload: '',
                    filePath: ''
                };
            }
        },
        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;
        },
        doSave() {
            const self = this;
            this.$refs.dataform.validateForm(() => {
                if (self.type == 'ADD') {
                    self.create();
                } else {
                    self.update();
                }
            });
        },
        create() {
            const self = this;
            const obj = this.deviceTypeList.find(el => el.value == this.formModel.deviceTypes);
            if (obj) {
                this.formModel.deviceTypes = [obj.code];
            }
            const data = {
                fileType: 'DRAWING',
                mapId: this.formModel.mapId,
                deviceTypes: this.formModel.deviceTypes,
                deviceIds: this.formModel.deviceIds,
                filePath: this.formModel.filePath
            };
            postUploadFile(data).then((res) => {
                self.$message.success('上传PDF成功!');
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                console.log(error);
                self.$message.error(`创建文章失败:${error.message}`);
            });
        },
        update() {
            const self = this;
            const obj = this.deviceTypeList.find(el => el.value == this.formModel.deviceTypes);
            if (obj) {
                this.formModel.deviceTypes = [obj.code];
            }
            const data = {
                id: this.id,
                fileType: 'DRAWING',
                mapId: this.formModel.mapId,
                deviceTypes: this.formModel.deviceTypes,
                deviceIds: this.formModel.deviceIds,
                filePath: this.formModel.filePath
            };
            putUploadFile(data).then(() => {
                self.$message.success('更新文章成功!');
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.$message.error(`更新文章失败:${error.message}`);
            });
        },
        handleClose() {
            this.formModel = {
                title: ''
            };
            this.$refs.dataform.resetForm();
            this.dialogVisible = false;
        }
    }
};
</script>

<style lang="scss" scoped>
.uploadDialog{
	/deep/ {
		.el-select--medium{
			width: 300px;
		}
	}
}
</style>
