<template>
    <el-form ref="attachmentFrom" v-loading="loading" :model="form" label-width="190px" size="small" :rules="rules"
        class="upload-temporary-file">
        <div class="base-dialog-body">
            <el-form-item :label="$t('dictionary:signature:form:FileName')" prop="Name">
                <el-input v-model="form.Name" clearable></el-input>
            </el-form-item>
            <el-form-item :label="$t('dictionary:signature:form:OffLine')" prop="OffLine">
                <el-switch v-model="form.OffLine" :active-value="true" :inactive-value="false"
                    :active-text="$fd('YesOrNo', true)" :inactive-text="$fd('YesOrNo', false)">
                </el-switch>
            </el-form-item>
            <el-form-item :label="$t('dictionary:signature:form:File')">
                <div class="upload-container">
                    <el-upload class="upload-demo" action :accept="this.accept.join(',')" :before-upload="beforeUpload"
                        :http-request="handleUploadFile" :on-preview="handlePreview" :on-remove="handleRemoveFile"
                        :show-file-list="true" :file-list="fileList" :limit="1" :on-exceed="handleExceed">
                        <el-button size="small" type="primary" :loading="btnLoading">{{ $t('common:button:check')
                            }}</el-button>
                        <span slot="tip" style="margin-left: 10px" class="el-upload__tip">
                            ({{ $t('trials:signature:label:type').replace("xxx", this.accept.join(", ")) }})
                        </span>
                    </el-upload>
                </div>
            </el-form-item>
        </div>
        <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
            <el-form-item style="text-align: right">
                <el-button size="small" type="primary" :disabled="form.FileTypeId === '' || form.Name === ''"
                    :loading="saveBtnLoading" @click="handleSave">{{ $t('common:button:save') }}</el-button>
            </el-form-item>
        </div>
    </el-form>
</template>
<script>
import { addOrUpdateSystemDocumentAttachment } from '@/api/dictionary'
export default {
    props: {
        data: {
            type: Object,
            default() {
                return {}
            },
        },
        SystemDocumentId: {
            type: String,
            default: ''
        }
    },

    data() {
        return {
            form: {
                Id: '',
                Name: null,
                FileFormat: null,
                FileName: null,
                FilePath: null,
                FileSize: null,
                OffLine: false,
                SystemDocumentId: null,
            },
            rules: {
                Name: [
                    {
                        required: true,
                        message: this.$t('common:ruleMessage:specify'),
                        trigger: ['change'],
                    },
                ],
            },
            fileList: [],
            btnLoading: false,
            saveBtnLoading: false,
            loading: false,
            accept: ['.jpg',
                '.jpeg',
                '.png',
                '.pdf',
                '.ppt',
                '.pptx',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx',
                '.mp4']
        }
    },
    mounted() {
        this.initForm()
    },
    methods: {
        async initForm() {
            this.loading = true
            if (this.data && this.data.Id) {
                Object.keys(this.form).forEach(key => {
                    this.form[key] = this.data[key]
                })
                this.fileList = [
                    {
                        name: this.data.FileName,
                        url: this.data.FilePath,
                        path: this.data.FilePath,
                    },
                ]
            }
            this.loading = false
        },
        beforeUpload(file) {
            // 检测文件类型是否符合要求
            if (this.checkFileSuffix(file.name)) {
                this.fileList = []
                return true
            } else {
                this.$alert(this.$t('trials:signature:label:type').replace("xxx", this.accept.join(", ")))

                return false
            }
        },
        async handleUploadFile(param) {
            this.loading = true
            var file = await this.fileToBlob(param.file)
            const res = await this.OSSclient.put(
                `/System/DocumentToSign/${param.file.name}${new Date().getTime()}`,
                file
            )
            this.fileList.push({
                name: param.file.name,
                path: this.$getObjectName(res.url),
                url: this.$getObjectName(res.url),
            })
            this.form.Name = param.file.name
            this.form.FileName = param.file.name
            this.form.FilePath = this.$getObjectName(res.url)
            this.form.FileSize = param.file.size
            this.form.FileFormat = param.file.name
                .substring(param.file.name.lastIndexOf('.'))
                .toLocaleLowerCase().split('.')[1]
            this.loading = false
        },
        handleSave() {
            this.$refs.attachmentFrom.validate((valid) => {
                if (!valid) return false
                if (!this.form.FilePath)
                    return this.$alert(this.$t('trials:signature:message:selectFile'))
                this.saveBtnLoading = true
                if (this.SystemDocumentId) this.form.SystemDocumentId = this.SystemDocumentId
                addOrUpdateSystemDocumentAttachment(this.form)
                    .then((res) => {
                        this.saveBtnLoading = false
                        this.$emit('closeDialog')
                        this.$emit('getList')
                        this.$message.success(this.$t('common:message:updatedSuccessfully'))
                    })
                    .catch(() => {
                        this.saveBtnLoading = false
                    })
            })
        },
        handleRemoveFile() {
            this.fileList = []
            this.form.FilePath = ''
            this.form.FileSize = ''
            this.form.FileFormat = ''
            this.form.FileName = ''
        },
        handlePreview(file) {
            if (file.fullPath) {
                window.open(file.fullPath, '_blank')
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(this.$t('upload:rule:maxFile1'))
        },
        checkFileSuffix(fileName) {
            var typeArr = this.accept.map(item => item.split('.')[1])
            var extendName = fileName
                .substring(fileName.lastIndexOf('.') + 1)
                .toLocaleLowerCase()
            if (typeArr.indexOf(extendName) !== -1) {
                return true
            } else {
                return false
            }
        },
    },
}
</script>

<style lang="scss">
.upload-temporary-file {
    .upload-container .el-upload--text {
        border: none;
        width: 80px;
        height: 40px;
    }

    .upload-container .el-input--small {
        margin-bottom: 5px;
    }

    .upload-container .el-icon-circle-check {
        color: #428bca;
        font-size: 13px;
    }

    .account_item_clear {
        .el-tag__close {
            display: none !important;
        }
    }
}
</style>