<script setup>
import { ref, reactive } from 'vue'
import { Search, CircleCheckFilled, CircleCloseFilled  } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {pdfInterface} from '@/api/modules/pdfApi.js'
import _ from 'lodash'

function handleOperate(type,data){
    if(type==='delete'){
        deletePDF(data)
        return
    }
    if(type==='showUrl'){
        pdfState.value=_.cloneDeep(data)
        showUrlDialog.value = true
        return
    }
    if(type==='add'){
        pdfState.value = {
            PdfId:0,
            PdfName:'',
            PdfUrl:''
        }
    }
    if(type==='edit'){
        pdfState.value = _.cloneDeep(data)
    }
    
    modifyPDFDialogShow.value = true
}
function deletePDF(data){
    //二次确认
    ElMessageBox.confirm('删除后不可恢复,是否确认删除?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(()=>{
        pdfInterface.deletePdf({
            PdfId:data.PdfId,
        }).then(res=>{
            if(res.Ret!==200) return 
            ElMessage.success('删除成功')
            handleCurrentChange(1)
        })
    }).catch(()=>{})
}

let tableLoading = ref(false)
let tableData = ref([])
const tableColumns = [
    {
        label:'文件名称',
        key:'PdfName'
    },{
        label:'PDF链接',
        key:'PdfUrl'
    },/* {
        label:'小程序链接',
        key:'ShareUrl'
    }, */{
        label:'更新时间',
        key:'ModifyTime'
    }]
let tableParams = reactive({
    pageNo:1,
    pageSize:10,
    total:0,
    dateRange:'',
    keyWord:''
})
function handleCurrentChange(page){
    tableParams.pageNo = page
    getTableData()
}

function getTableData(){
    tableLoading.value = true
    pdfInterface.getPdfList({
        PageSize:tableParams.pageSize,
        CurrentIndex:tableParams.pageNo,
        Keyword:tableParams.keyWord,
        StartTime:tableParams.dateRange?tableParams.dateRange[0]||'':'',
        EndTime:tableParams.dateRange?tableParams.dateRange[1]||'':''
    }).then(res=>{
        if(res.Ret!==200) return 
        tableLoading.value = false
        tableData.value = res.Data.List
        tableParams.total = res.Data.Paging.Totals
    })
}
getTableData()

let pdfState = ref({
    PdfId:0,//新增0,编辑非0,
    PdfName:'',
    PdfUrl:'',
    ShareUrl:'',
    OriginName:''
})
let modifyPDFDialogShow = ref(false)
let isUploading = ref(false)
let uploadRef = ref(null)
let formRef = ref(null)
const formRules = reactive({
    PdfName:[{required:true,message:'文件名称不能为空'},{max:30,message:'文件名称不能超过30个字符'}],
    PdfUrl:[{validator:(rule,value,callback)=>{
        if(!pdfState.value.PdfUrl){
            return callback(new Error('请上传文件'))
        }else{
            callback()
        }
    }}]
})
//点击上传按钮
function handleUpload(){
    if(pdfState.value.PdfUrl.length) return
    uploadRef.value?.$el.getElementsByTagName('input')[0].click()
}
async function handleUploadPdf(e){
    if(e.file.type!=='application/pdf'){
        ElMessage.warning('请选择pdf格式的文件!')
        return
    }
    isUploading.value = true
    let form = new FormData()
    form.append("file", e.file)
    const res = await pdfInterface.uploadPdf(form)
    if(res.Ret===200){
        pdfState.value.PdfUrl = res.Data
        pdfState.value.PdfName = e.file.name.slice(0,-4).trim()
        pdfState.value.OriginName = e.file.name.slice(0,-4).trim()
        isUploading.value = false
        formRef.value?.clearValidate();
    }
}
async function handleChangePDF(){
    let flag = false
    await formRef.value.validate((valid) => {
        flag = valid
    })
    if(!flag) return
    pdfState.value.PdfId===0?addPDF():editPDF()
}
function addPDF(){
    const {PdfName,PdfUrl,OriginName} = pdfState.value
    pdfInterface.addPdf({
        PdfName,PdfUrl,OriginName
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('添加成功')
        handleCurrentChange(1)
        modifyPDFDialogShow.value=false
    })
}
function editPDF(){
    const {PdfId,PdfName,PdfUrl,OriginName} = pdfState.value
    pdfInterface.editPdf({
        PdfId,PdfName,PdfUrl,OriginName
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('编辑成功')
        handleCurrentChange(1)
        modifyPDFDialogShow.value=false
    })
}
//移除已上传的文件
function handleRemove(){
    if(isUploading.value) return
    pdfState.value.PdfUrl = ''
    pdfState.value.PdfName=''
}

let showUrlDialog = ref(false)

/* //复制小程序链接(砍掉的功能)
async function copyLink(data){
    try{
        await navigator.clipboard.writeText(data.ShareUrl)
        ElMessage.success('复制成功')
    }catch(err){
        ElMessage.error('复制失败')
    }
} */
</script>

<template>
    <div class="pdf-list-wrap">
        <div class="head-wrap container-wrap">
            <el-button type="primary" @click="handleOperate('add',{})">添加文件</el-button>
            <div class="select-box">
                <el-date-picker
                    style="margin-right:20px;"
                    v-model="tableParams.dateRange"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期" @change="handleCurrentChange(1)">
                    </el-date-picker>
                <el-input placeholder="请输入文件名称" 
                    v-model="tableParams.keyWord"
                    :prefix-icon="Search"
                    @input="handleCurrentChange(1)"
                    clearable
                    style="width:240px;"
                ></el-input>
            </div>
        </div>
        <div class="table-wrap container-wrap">
            <el-table border :data="tableData" v-loading="tableLoading">
                <el-table-column 
                    v-for="column in tableColumns" :key="column.key" 
                    :label="column.label" align="center">
                    <template #default="{row}">
                        <span v-if="column.key==='PdfUrl'" class="text-ellipsis" :title="row.PdfUrl">
                            <a :href="row.PdfUrl" 
                                target="_blank" 
                                style="color:#409EFF;"
                            >{{row.PdfUrl}}</a>
                        </span>
                        <!-- <div v-else-if="column.key==='ShareUrl'" class="cell-item-copy">
                            <span class="text-ellipsis">{{row.ShareUrl}}</span>
                            <span class="copy-btn" @click="copyLink(row)">复制</span>
                        </div> -->
                        <span v-else class="text-ellipsis">{{row[column.key]}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="{row}">
                        <span style="cursor: pointer;color:#66b1ff;margin-right: 20px;" @click="handleOperate('edit',row)">编辑</span>
                        <span style="cursor: pointer;color:#66b1ff;margin-right: 20px;" @click="handleOperate('showUrl',row)">微信分享</span>
                        <span style="cursor: pointer;color:red;" @click="handleOperate('delete',row)">删除</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination layout="total,prev,pager,next,jumper" background :current-page="tableParams.pageNo"
                @current-change="handleCurrentChange" :page-size="tableParams.pageSize" :total="tableParams.total"
                style="justify-content: flex-end; margin-top: 20px">
            </el-pagination>
        </div>
    </div>
    <!-- 添加/编辑pdf弹窗 -->
    <el-dialog
        v-if="modifyPDFDialogShow" 
        v-model="modifyPDFDialogShow" 
        :close-on-click-modal="false" 
        :modal-append-to-body="false"
        width="689px" center
        :title="`${pdfState.PdfId===0?'新增':'编辑'}文件`"
        @close="modifyPDFDialogShow=false"
        class="modify-dialog"
    >
        <div class="dialog-container">
            <el-form
                ref="formRef"
                label-position="left"
                hide-required-asterisk
                label-width="80px"
                :model="pdfState"
                :rules="formRules"
                >
                <el-form-item label="上传文件" prop="PdfUrl" class="upload-form-item">
                    <el-button  type="primary" :disabled="Boolean(pdfState.PdfUrl.length)" :loading="isUploading" @click.stop="handleUpload">{{`${isUploading?'正在':'点击'}`}}上传</el-button>
                    <el-upload
                        ref="uploadRef"
                        action=""
                        accept="application/pdf"
                        :http-request="handleUploadPdf"
                        :show-file-list="false"
                        style="display: flex;"
                    >
                    </el-upload>
                    <div class="file-item" v-if="pdfState.PdfUrl.length">
                        <img src="~@/assets/img/pdf-icon.png" alt="" class="file-icon">
                        <span class="file-name">{{`${pdfState.OriginName||''}.pdf`}}</span>
                        <span class="status-icon" @click="handleRemove">
                            <el-icon class="success"><CircleCheckFilled /></el-icon>
                            <el-icon class="close"><CircleCloseFilled /></el-icon>
                        </span>
                    </div>
                </el-form-item>
                
                <el-form-item label="文件名称" prop="PdfName">
                    <el-input
                    v-model="pdfState.PdfName"
                    style="width: 80%"
                    placeholder="请输入文件名称"
                    />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="foot-container">
                <el-button type="primary" @click="handleChangePDF">确 定</el-button>
                <el-button @click="modifyPDFDialogShow=false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 微信分享弹窗 -->
    <el-dialog
        v-if="showUrlDialog" 
        v-model="showUrlDialog" 
        :close-on-click-modal="false" 
        :modal-append-to-body="false"
        width="689px" center
        title="微信分享"
        @close="showUrlDialog=false"
        class="share-dialog"
    >
        <div class="share-dialog-container">
            <p>{{pdfState.PdfName}}</p>
            <img :src="pdfState.ShareUrl" alt="" v-if="pdfState.ShareUrl">
            <p v-else style="color:#999;margin:30px 0;">分享链接还未生成,请稍后刷新重试</p>
            <el-button type="primary" @click="showUrlDialog=false">知道了</el-button>
        </div>
    </el-dialog>
</template>

<style scoped lang="scss">
.pdf-list-wrap{
    .text-ellipsis{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .container-wrap{
        padding:20px;
        background-color: #fff;
        border-radius: 4px;
    }
    .head-wrap{
        display: flex;
        justify-content: space-between;
        .select-box{
            margin-left: auto;
        }
    }
    .table-wrap{
        margin-top:20px;
        box-sizing: border-box;
        min-height: calc(100vh - 222px);
        .cell-item-copy{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .copy-btn{
                padding:4px 14px;
                background-color: #ECF5FF;
                border: 1px solid #B3D8FF;
                border-radius: 4px;
                color:#409EFF;
                cursor: pointer;
                margin-left: 5px;
                min-width: 60px;
                box-sizing: border-box;
            }
        }
        
    }
}
.modify-dialog{
    .dialog-container{
        .file-item{
            display: flex;
            align-items: center;
            margin-left: 15px;
            img{
                display: inline-block;
                width:18px;
                margin-right: 12px;
            }
            .file-name{
                color:#999999;
                margin-right: 20px;
            }
            .status-icon{
                display: flex;
                font-size: 16px;
                color: #67C23A;
                .success{
                    display: inline-flex;
                }
                .close{
                    color: #999999;
                    display: none;
                }
            }
            &:hover{
                .status-icon .success{
                    display: none;
                }
                .status-icon .close{
                    display: inline-flex;
                }
            }
        }
    }
}
.share-dialog{
    .share-dialog-container{
        text-align: center;
        img{
            display: block;
            width:300px;
            margin: 30px auto;
        }
        .el-button{
            margin-bottom: 25px;
        }
    }
}
</style>
