<template>
    <div class="layout-pd">
        <el-row>
            <!-- 操作 -->
            <el-col :xs="24">
                <el-card class="mt8" shadow="hover">
                    <el-form :model="qrBookData.Filter" :inline="true" @submit.stop.prevent>
                        <el-form-item prop="name" style="width: 100%;">
                            <el-col :xs="15" :sm="6" :md="5" :lg="5" class="mb20">
                                <el-form-item label="上传人">
                                    <el-input v-model="qrBookData.Filter.Author" placeholder="单行输入" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" class="mb20">
                                <el-form-item label="说明书名称">
                                    <el-input v-model="qrBookData.Filter.FileName" placeholder="单行输入" clearable></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :xs="24" :md="8" :lg="8" :xl="4" class="mb20">
                                <el-form-item label="选择时间">
                                    <el-date-picker
                                        v-model="qrBookData.time"
                                        type="datetimerange"
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                        range-separator="To"
                                        start-placeholder="Start date"
                                        end-placeholder="End date" />
                                </el-form-item>
                            </el-col>

                            <el-col :xs="24" :md="8" :lg="8" :xl="4" class="mb20">
                                <el-form-item>
                                    <el-button type="primary" icon="ele-Search" @click="getData()">查询</el-button>
                                    <el-button type="primary" plain icon="ele-RefreshRight" @click="clear()">清空</el-button>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                        
                        <div class="my-flex my-flex-end">
                            <el-button type="primary" icon="ele-CirclePlus" @click="uploadDialog">上传说明书</el-button>
                        </div>
                    </el-form>
                </el-card>
            </el-col>

            <!-- 表格 -->
             <el-col :xs="24">
                <el-card style="height: 70vh;" class="my-fill mt8" shadow="hover">
                    <el-table v-loading="qrBookData.loading" stripe :data="qrBookData.tableModel" row-key="id" style="width: 100%;">
                        <el-table-column v-for="column in qrBookData.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label">
                            <template #default="{row}">
                                <span :style="getColor(column.prop,row)">
                                    {{getName(column.prop,row)}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" align="center" header-align="center" class="right-operation" width="140">
                            <template #default="{row}">
                                <el-link class="my-el-link mr12 ml12" type="primary" :underline="false" target="_blank" icon="ele-Edit" @click="editDialog(row)">编辑</el-link>
                                <el-link class="my-el-link mr12 ml12"  type="primary" :underline="false" target="_blank" icon="ele-Download" @click="download(row,0)">下载文件</el-link>
                                <el-link class="my-el-link mr12 ml12"  type="primary" :underline="false" target="_blank" icon="ele-Download" @click="download(row,1)">下载二维码</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="my-flex my-flex-end" style="margin-top: 20px">
                        <el-pagination
                            v-model:currentPage="qrBookData.PageInput.CurrentPage"
                            v-model:page-size="qrBookData.PageInput.PageSize"
                            :total="qrBookData.total"
                            :page-sizes="[10, 20, 50, 100]"
                            small
                            background
                            @size-change="onSizeChange"
                            @current-change="onCurrentChange"
                            layout="total, sizes, prev, pager, next, jumper"/>
                    </div>
                    <template>
                        <a ref="downloadLink" style="display: none;"></a>
                    </template>
                </el-card>
             </el-col>
        </el-row>
        <FileEditDialog ref="fileEditRef"></FileEditDialog>
    </div>
    
</template>

<script setup lang="ts">
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { QRBookFilter, QRBookPageSearchResponse } from "/@/api/admin/productionManagement/QRBookDto";
import { pageInput } from "/@/api/admin/shareDto/shareDto";
import { QRBookApi } from "/@/api/admin/productionManagement/qrBookApi";
import eventBus from "/@/utils/mitt";
import { useGlobalCacheStore } from "/@/stores/globalCacheStore";

/**引入组件*/
const FileEditDialog = defineAsyncComponent(() => import('./components/qrbook-edit.vue'))
const fileEditRef = ref()

/** 获取全局缓存 */
const globalCacheStore = useGlobalCacheStore()
  /** 获取文件状态 */
  const statusType = ref(globalCacheStore.getGlobalStore().get('qrBookFileStatus'))

const downloadLink = ref()

const qrBookData = reactive({
    // 是否加载
    loading : false,
    time:'',
    // 查询条件
    Filter:{
        Author:"",
        FileName:"",
        StartTime: null,
        EndTime: null
    } as QRBookFilter,
    // 表数据
    tableModel:[] as QRBookPageSearchResponse[],
    // 表头
    dynamicColumns: [
        { prop: 'fileName', label: '说明书文件名' },
        { prop: 'author', label: '上传人' },
        { prop: 'status', label: '状态' },
        { prop: 'uploadTime', label: '上传时间' },
        { prop: 'updateTime', label: '修改时间' },
        { prop: 'remark', label: '备注' }
    ],
    /**分页标识 */
    PageInput:{
        CurrentPage: 1,
        PageSize: 10,
  } as pageInput,
  /**分页总数 */
  total: 0
})

//获取数据
const getData = async () => {
    qrBookData.loading = true
    let res = await new QRBookApi().getPage({
        ...qrBookData.PageInput,
        "Filter.Author":qrBookData.Filter.Author,
        "Filter.FileName":qrBookData.Filter.FileName,
        "Filter.StartTime":qrBookData.Filter.StartTime,
        "Filter.EndTime":qrBookData.Filter.EndTime
    })
    qrBookData.tableModel = res?.data?.list ?? []
    qrBookData.total = res?.data?.total ?? 0
    qrBookData.loading = false
}

//清除查询条件
const clear = () => {
    qrBookData.Filter = {
        author:"",
        fileName:"",
        startTime: null,
        endTime: null
    } as QRBookFilter

}

//下载
const download = async (row,type) => {
    let fileName = ""
    switch(type) {
        case 0:
            fileName = removeExtension(row.fileName) + row.extension
            break
        case 1:
            fileName = removeExtension(row.fileName) + ".PNG"
            break
    }
    let res = await new QRBookApi().donwloadFile(row.id,type,fileName)
    
}
//去除文件名后缀
const removeExtension = (filename:string) => {
    const dotIndex = filename.lastIndexOf('.');  
    if (dotIndex < 0) {  
        // 如果没有找到'.'，则返回原始文件名  
        return filename;  
    }  
    // 返回去除最后一个'.'及其之后的所有字符的字符串  
    return filename.slice(0, dotIndex);  
}

//打开上传文件弹窗
const uploadDialog = () => {
    fileEditRef.value.openDialog()
}
//打开编辑文件弹窗
const editDialog = (row) => {
    fileEditRef.value.openDialog(row)
}

const onSizeChange = () => {
    getData()
}

const onCurrentChange = () => {
    getData()
}

//获取颜色值
const getColor = (val,row) => {
    if(val === "status") return {color: statusType.value.get(String(row[val])).color}
    return {}
}

//获取名称值
const getName = (val,row) => {
    if(val === "status") return statusType.value.get(String(row[val])).name
    return row[val]
}

watch(() => qrBookData.time,(val) => {
    if(val?.length === 0) return
    qrBookData.Filter.StartTime = val?.[0].toString()
    qrBookData.Filter.EndTime = val?.[1].toString()
})

onMounted(() => {
    getData()
    eventBus.off('refreshView')
    eventBus.on('refreshView', async () => {
        await getData()
    })
})

onBeforeMount(() => {
    eventBus.off('refreshView')
})

</script>