<template>
    <div>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
                    导出
                </el-button>
            </el-col>
        </el-row>
        <el-table v-loading="loading" :data="equipmentList">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="物资名称" align="center" prop="maTypeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column
                label="单位"
                align="center"
                prop="unitName"
                :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
                label="采购数量"
                align="center"
                prop="purchaseNum"
                :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
                label="购置单价（元含税）"
                align="center"
                prop="purchaseTaxPrice"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="购置单价（元不含税）"
                align="center"
                prop="purchasePrice"
                :show-overflow-tooltip="true"
            />
            <el-table-column label="租赁价(元/天)" align="center" prop="rentPrice" :show-overflow-tooltip="true" />
            <el-table-column label="是否未固定资产" align="center" prop="fixCode" :show-overflow-tooltip="true" />
            <el-table-column label="出厂日期" align="center" prop="productionTime" :show-overflow-tooltip="true" />
            <el-table-column label="相关配套资料" align="center" prop="">
                <template slot-scope="scope">
                    <div
                        style="color: #02a7f0; cursor: pointer"
                        @click="openFileDialog(scope.row)"
                        v-if="scope.row.isExitFile == 1"
                    >
                        报告管理
                    </div>
                    <div
                        style="color: red; cursor: pointer"
                        @click="openFileDialog(scope.row)"
                        v-if="scope.row.isExitFile == 0"
                    >
                        报告管理
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.purchase_task_status" :value="scope.row.status" />
                </template>
            </el-table-column>
        </el-table>

        <el-dialog title="报告管理" :visible.sync="open" width="900px" append-to-body>
            <el-table :data="fileDataList" width="100%" height="350px">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="报告类型" align="center" prop="dictLabel" :show-overflow-tooltip="true" />
                <el-table-column label="类型名称" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.maTypeName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.typeName }}</div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="报告日期" align="center" prop="orgName" :show-overflow-tooltip="true"/>
                <el-table-column label="截止有效期" align="center" prop="orgName" :show-overflow-tooltip="true"/> -->
                <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <el-upload
                                ref="upload"
                                :headers="upload.headers"
                                :action="upload.url"
                                :show-file-list="false"
                                accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                                :on-success="(res, file, fileList) => handleFileSuccess(scope.row, res, file, fileList)"
                                :auto-upload="true"
                            >
                                <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
                            </el-upload>

                            <el-button
                                size="mini"
                                type="text"
                                @click="picturePreviewFile(scope.row)"
                                v-if="scope.row.fileListTemp != 0"
                            >
                                查看
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 图片查看弹窗 -->
        <el-dialog :visible.sync="dialogVisible" width="500px" height="500px">
            <img width="100%" height="500px" :src="dialogImageUrl" />
        </el-dialog>

        <!-- 文件查看列表 -->
        <el-dialog title="文件列表" :visible.sync="dialogVisibleFile" width="500px" height="500px">
            <el-table :data="fileListInfo" width="100%" height="350px" style="overflow: auto">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="文件名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="picturePreview(scope.row)" v-if="scope.row.url">
                            查看
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleDelete(scope.row)"
                            v-if="scope.row.url"
                            style="color: red"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { getPurchaseCheckInfo } from '@/api/purchase/goodsArrived'
import {
    uploadPurchaseFile,
    getPurchaseFileList,
    bmFileInfoAddApi,
    bmFileInfoRemoveApi
} from '@/api/purchase/goodsAccept'
import { getToken } from '@/utils/auth'
export default {
    name: 'QueryTools',
    dicts: ['purchase_task_status'],
    components: {
        // UploadImg,
    },
    props: {
        isView: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        queryTaskId: {
            type: [String, Number],
            default: () => {
                return ''
            }
        },
        queryId: {
            type: [String, Number],
            default: () => {
                return ''
            }
        }
    },
    data() {
        return {
            fixCodeList: ['否', '是'],
            //任务ID
            taskId: '',
            // 遮罩层
            loading: true,
            //任务数据
            taskInfo: {},
            // 表格数据
            equipmentList: [],
            // 是否显示弹出层
            open: false,
            rowData: {},
            fileDataList: [
                { dictLabel: '合格证', fileType: '0', name: '', url: '' },
                { dictLabel: '型式试验报告', fileType: '1', name: '', url: '' },
                { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '' },
                { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '' },
                { dictLabel: '其他', fileType: '4', name: '', url: '' }
            ],
            fileListInfo: [],
            //上传
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/file/upload'
            },
            //图片查看弹窗
            dialogImageUrl: '',
            dialogVisible: false,
            dialogVisibleFile: false
        }
    },
    computed: {},
    mounted() {
        this.taskId = this.queryTaskId
        this.id = this.queryId
        this.getTaskInfo()
    },
    methods: {
        //获取任务详情-列表数据
        getTaskInfo() {
            this.loading = true
            getPurchaseCheckInfo({ taskId: this.taskId, id: this.id, taskStage: 1 }).then(response => {
                this.taskInfo = response.data
                this.equipmentList = response.data.purchaseCheckDetailsList
                this.equipmentList.forEach(item => {
                    item.fixCode = this.fixCodeList[Number(item.fixCode)]
                })
                this.loading = false
            })
        },
        //文件管理
        openFileDialog(row) {
            this.rowData = row
            this.fileDataList = [
                { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
            ]
            this.getFileData()
            this.open = true
        },
        async getFileData() {
            this.fileDataList = [
                { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
                { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
            ]
            let param = {
                modelId: this.rowData.typeId,
                taskType: 0,
                taskId: this.rowData.taskId,
                pageNum: 1,
                pageSize: 9999999
            }
            await getPurchaseFileList(param)
                .then(response => {
                    if (response.rows.length > 0) {
                        console.log('xxxxxxxxxxx')
                        response.rows.forEach(item => {
                            let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)

                            this.fileDataList[index].fileList.push({
                                name: item.name,
                                url: item.url
                            })

                            this.fileDataList[index].fileListTemp.push({
                                name: item.name,
                                url: item.url,
                                id: item.id
                            })
                        })
                    }
                })
                .catch(() => {})
        },
        beforeFileUpload(row) {
            console.log('🚀 ~ beforeFileUpload ~ row:', row)
            this.rowData.fileType = row.fileType
        },

        beforeUpload(row, file) {
            row.fileList.push(file)
            console.log('6666666', row.fileList)
            if (row.fileList.length > 3) {
                this.$message.warning('最多只能上传三张图片')
                // 删除最后一个文件
                row.fileList.pop()
                return false // 阻止上传
            }
            return true // 允许上传
        },
        // 文件上传成功处理
        handleFileSuccess(row, response, file, fileList) {
            console.log('🚀 ~ handleFileSuccess ~ row:', row)
            if (response.code == 200) {
                //编辑逻辑
                // row.fileListTemp.push({
                //   name: response.data.name,
                //   url: response.data.url
                // })
                let obj = {
                    taskId: this.taskId,
                    taskType: '0',
                    name: response.data.name,
                    url: response.data.url,
                    modelId: this.rowData.typeId,
                    fileType: this.rowData.fileType
                }
                console.log('🚀 ~ handleFileSuccess ~ obj:', obj)
                bmFileInfoAddApi(obj).then(res => {
                    setTimeout(() => {
                        this.getFileData()
                    }, 500)
                })
            }
        },

        picturePreviewFile(row) {
            this.fileListInfo = row.fileListTemp

            this.dialogVisibleFile = true
        },
        //图片查看
        picturePreview(file) {
            this.dialogImageUrl = file.url.replaceAll('#', '%23')
            const parts = file.name.split('.')
            const extension = parts.pop()
            if (
                extension === 'doc' ||
                extension === 'DOC' ||
                extension === 'docx' ||
                extension === 'DOCX' ||
                extension === 'pdf' ||
                extension === 'PDF'
            ) {
                const windowName = file.name
                window.open(file.url, windowName)
            } else {
                this.dialogVisible = true
            }
        },
        // 删除图片
        handleDelete(row) {
            console.log('🚀 ~ handleDelete ~ row:', row)
            // 弹框确认
            this.$modal.confirm('是否确认删除所选择图片？').then(() => {
                bmFileInfoRemoveApi([row.id]).then(res => {
                    this.dialogVisibleFile = false
                    this.getFileData()
                })
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            const formatTime = date => {
                const year = date.getFullYear()
                const month = String(date.getMonth() + 1).padStart(2, '0')
                const day = String(date.getDate()).padStart(2, '0')
                const hours = String(date.getHours()).padStart(2, '0')
                const minutes = String(date.getMinutes()).padStart(2, '0')
                const seconds = String(date.getSeconds()).padStart(2, '0')
                return `${year}${month}${day}_${hours}${minutes}${seconds}`
            }

            const currentTime = formatTime(new Date())
            this.download(
                '/material/purchase_check_info/exportDetails',
                { taskId: this.taskId, id: this.id, taskStage: 1 },
                `新购到货详情_${currentTime}.xlsx`
            )
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
//隐藏图片上传框的css
::v-deep.disabled {
    .el-upload--picture-card {
        display: none;
    }
}
.custom-textarea {
    width: 300px;
    height: 100px;
}
.accept-img {
    color: #409eff;

    .a-two {
        margin-left: 20px;
    }
}

.left-tip {
    font-size: 16px;
    letter-spacing: 1px;
}
</style>
