<template>
    <div v-if="config.visible">
        <base-model :config="config">
            <template slot="dialog-body">
                <el-form ref="form" :model="rowData" label-width="80px" style="width: 80%;display: inline-block;">
                    <el-form-item :label="`${$t('trials:trialDocument:table:Name')}: `">
                        <span class="name text-ellipsis" :title="rowData.Name">{{ rowData.Name }}</span>
                    </el-form-item>
                </el-form>
                <el-button size="mini" type="primary" style="float:right" @click.stop="openFile(true)">
                    {{ $t('trials:trialDocument:historyFileList:button:addFolder') }}</el-button>
                <div style="float:right;padding: 0 5px;width: 10px;height: 10px;"></div>
                <el-button size="mini" type="primary" style="float:right" @click.stop="openFile(false)">
                    {{ $t('trials:trialDocument:historyFileList:button:addFile') }}</el-button>
                <el-table :data="list" style="width: 100%" max-height="300px" v-loading="loading"
                    @sort-change="handleSortByColumn" @cell-mouse-enter="handleCellMouseEnter">
                    <el-table-column type="index" width="60" />
                    <el-table-column prop="FileName" :label="$t('trials:trialDocument:historyFileList:FileName')"
                        sortable="custom" width="200px">
                        <template slot-scope="scope">
                            <div v-if="renameId !== scope.row.Id" class="name_box">
                                <span class="name" :title="scope.row.FileName">{{ scope.row.FileName }}</span>
                                <i class="el-icon-edit icon_edit" @click="addRenameId(scope.row)"
                                    :title="$t('trials:trialDocument:historyFileList:icon:rename')" />
                            </div>


                            <el-input v-model="scope.row.FileName" :ref="`renameInp_${scope.row.Id}`" :autofocus="true"
                                class="renameInp" @blur="save(scope.row)" v-else />
                        </template>
                    </el-table-column>
                    <el-table-column prop="FileFormat" :label="$t('trials:trialDocument:historyFileList:FileType')"
                        sortable="custom" />
                    <el-table-column prop="FileSize" :label="$t('trials:trialDocument:historyFileList:FileSize')"
                        sortable="custom">
                        <template slot-scope="scope">
                            <span>{{
                                $FormatSize(scope.row.FileSize)
                                }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CreateTime" :label="$t('trials:trialDocument:historyFileList:CreateTime')"
                        sortable="custom" />
                    <el-table-column :label="$t('common:action:action')" min-width="120px">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click.stop="preview(scope.row)">
                                {{ $t('common:button:preview') }}
                            </el-button>
                            <el-button size="mini" type="text" @click.stop="del(scope.row)">
                                {{ $t('common:button:delete') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </base-model>
        <viewer ref="picture_perview4" style="margin: 0 10px"
            v-if="rowDATA.FileFormat && ['png', 'jpg', 'jpeg'].includes(rowDATA.FileFormat.toLowerCase())"
            :images="[`${OSSclientConfig.basePath}${rowDATA.FilePath}`]" :options="viewerOptions">

            <img v-show="false" :src="`${OSSclientConfig.basePath}${rowDATA.FilePath}`" alt="Image" />
        </viewer>
        <upload-files :config="upload_config" :faccept="faccept" :uploadPath="uploadPath" v-if="upload_config.visible"
            @close="close" @uplaodFile="uplaodFile" />
    </div>
</template>
<script>
import BaseModel from '@/components/BaseModel'
import uploadFiles from './uploadFiles.vue'
import { addOrUpdateTrialHistoryRecordFile, batchAddTrialHistoryRecordFile, getTrialHistoryRecordFileList, deleteTrialHistoryRecordFile } from '@/api/dictionary'
const defaultSearchData = () => {
    return {
        PageIndex: 1,
        PageSize: 1000,
        Asc: false,
        OffLine: null,
        SortField: null
    }
}
export default {
    components: {
        BaseModel,
        uploadFiles
    },
    props: {
        config: {
            type: Object,
            default: () => {
                return {
                    visible: false,
                    title: this.$t('trials:trialDocument:historyFileList:title'),
                    width: '800px',
                }
            }
        },
        rowData: {
            type: Object,
            default: () => {
                return {}
            }
        },
        uploadPath: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            searchData: defaultSearchData(),
            visible: false,
            title: null,
            list: [],
            rowDATA: {},
            loading: false,
            viewerOptions: {
                toolbar: {
                    zoomIn: true,
                    zoomOut: true,
                    reset: true,
                    prev: false,
                    next: false,
                    rotateLeft: true,
                    rotateRight: true,
                    flipHorizontal: true,
                    flipVertical: true,
                }
            },
            upload_config: {
                visible: false,
                showClose: true,
                width: '800px',
                title: '',
                appendToBody: false,
                isFolder: false,
            },
            faccept: ['.jpg',
                '.jpeg',
                '.png',
                '.pdf',
                '.ppt',
                '.pptx',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx',
                ".mp4",
                ".zip"],
            renameId: null
        }
    },
    watch: {
        'rowData.Id': {
            handler() {
                if (this.rowData.Id) {
                    console.log(this.rowData)
                    this.getList()
                }
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        // 单行hover移入
        handleCellMouseEnter(row) {
            this.hoverId = row.Id
        },
        addRenameId(row) {
            this.renameId = row.Id
            this.$nextTick(() => {
                if (this.$refs[`renameInp_${row.Id}`]) {
                    this.$refs[`renameInp_${row.Id}`].focus()
                }
            })
        },
        close() {
            this.upload_config.visible = false
        },
        getAllList() {
            this.getList()
            this.$emit("getList")
        },
        openAudit(row) {
            this.form = Object.assign({}, row)
            this.visible = true
        },
        async save(row) {
            try {
                if (!row.FileName) {
                    this.$message.warning(this.$t("trials:trialDocument:historyFileList:message:fileNameMust"))
                    return this.addRenameId(row)
                }

                this.renameId = null
                let res = await addOrUpdateTrialHistoryRecordFile(row)
                if (res.IsSuccess) {
                    this.getList()
                }
            } catch (err) {
                console.log(err)
            }
        },
        async del(row) {
            try {
                let confirm = await this.$confirm(this.$t("trials:trialDocument:historyFileList:message:del"))
                if (!confirm) return false
                this.loading = true
                let res = await deleteTrialHistoryRecordFile(row.Id)
                this.loading = false
                if (res.IsSuccess) {
                    this.getAllList()
                }
            } catch (err) {
                console.log(err)
                this.loading = false
            }
        },
        async uplaodFile(list) {
            console.log(list, 'list')
            try {
                let arr = []
                list.forEach(item => {
                    let obj = Object.assign({}, item)
                    obj.TrialFileTypeId = this.rowData.TrialFileTypeId
                    obj.TrialRecordId = this.rowData.Id
                    arr.push(obj)
                });
                this.loading = true
                let res = await batchAddTrialHistoryRecordFile(arr)
                this.loading = false
                if (res.IsSuccess) {
                    this.getAllList()
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        openFile(isFolder = false) {
            this.upload_config.title = this.$t(
                'trials:trialDocument:fileRecord:form:title:uploadFile'
            )
            this.upload_config.visible = true
            this.upload_config.isFolder = isFolder
        },
        async getList() {
            try {
                if (!this.rowData.Id) return false
                this.searchData.TrialRecordId = this.rowData.Id
                let res = await getTrialHistoryRecordFileList(this.searchData)
                this.loading = false
                if (res.IsSuccess) {
                    this.list = res.Result.CurrentPageData
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        preview(data) {
            // return this.perview_visible = true
            this.rowDATA = Object.assign({}, data)
            if (['.ppt',
                '.pptx',
                '.doc',
                '.docx',
                '.xls',
                '.xlsx'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$onlyOffice({
                    path: data.FilePath,
                    type: data.FileFormat,
                    title: data.Name
                })
            }
            if (['.jpg',
                '.jpeg',
                '.png'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$nextTick(() => {
                    this.$refs['picture_perview4'].$viewer.show()
                })
            }
            if (['.pdf'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$preview({
                    path: data.Path || data.FilePath,
                    type: 'pdf',
                    title: data.Name,
                })
            }
            if (['.mp4'].includes(`.${data.FileFormat.toLowerCase()}`)) {
                this.$video({
                    path: data.Path || data.FilePath,
                    type: 'mp4',
                    title: data.Name,
                })
            }
        },
        // 排序
        handleSortByColumn(column) {
            if (column.order === 'ascending') {
                this.searchData.Asc = true
            } else {
                this.searchData.Asc = false
            }
            this.searchData.SortField = column.prop
            this.searchData.PageIndex = 1
            this.getList()
        },
    }

}
</script>
<style lang="scss" scoped>
.name {
    display: block;
    width: 90%;
}

.name_box {
    display: flex;
    align-items: center;
    width: calc(100% - 20px);

    .name {
        max-width: calc(100% - 60px);
        white-space: nowrap;
        /* 文本不换行 */
        overflow: hidden;
        /* 超出部分隐藏 */
        text-overflow: ellipsis;
    }
}

.icon_edit {
    cursor: pointer;
    color: rgba(0, 0, 0, 0.3);
    margin-left: 2px;

    &:hover {
        color: rgba(0, 0, 0, 0.5);
    }
}

.renameInp {
    ::v-deep .el-input__inner {
        line-height: 23px;
        height: 23px;
    }
}
</style>