<template>
    <div class="mod-user">
        <div class="search-bar">
            <el-form :inline="true" class="search-form" ref="searchForm" :model="searchForm" size="small">
                <div class="input-row">
                    <el-form-item prop="orderNumber" label="订单编号:">
                        <el-input v-model="searchForm.orderNumber" type="text" clearable placeholder="订单编号"></el-input>
                    </el-form-item>
                  <el-form-item prop="pdfName" label="文件名:">
                    <el-input v-model="searchForm.pdfName" type="text" clearable placeholder="文件名"></el-input>
                  </el-form-item>
                    <el-form-item label="生成时间:">
                        <el-date-picker size="small" v-model="createDateRange" type="datetimerange"
                                        :default-time="['00:00:00', '23:59:59']"
                            range-separator="至" value-format="yyyy-MM-dd HH:mm:ss"
                            :start-placeholder="$t('text.startTime')" end-placeholder="结束日期"
                            @change="createTimeChange"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <div class="default-btn primary-btn" @click="searchChange(true)">{{ $t('crud.searchBtn') }}</div>
                        <div class="default-btn" @click="resetForm('searchForm')">重置</div>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <div class="main-container">
            <div class="operation-bar">
                <div class=" default-btn" @click="downLoadZIP()"
                    :disabled="importDisabled">批量下载ZIP</div>
            </div>
            <div class="table-con">
                <el-table :data="dataList" header-cell-class-name="table-header" row-class-name="table-row-low"
                    style="width: 100%">
                    <el-table-column prop="orderNumber" width="300" label="订单号" />
                    <el-table-column fixed label="文件名" prop="pdfName" align="left" />
                    <el-table-column fixed prop="pdfUrl" label="文件地址">
                        <template slot-scope="scope">
                            <div class="">
                                <a target="blank" :href="resourcesUrl + scope.row.pdfUrl">
                                    {{ scope.row.pdfUrl }}</a>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column width="230" prop="createTime" label="创建时间" />
                    <el-table-column width="230" prop="orderTime" label="下单时间" />
                    <el-table-column fixed="right" align="center" :label="$t('crud.menu')" width="230">
                        <template slot-scope="scope">
                            <div class="text-btn-con">
                              <div class="default-btn text-btn" @click="downLoadPDF(scope.row)">下载PDF文件</div>
                              <div class="default-btn text-btn" style="color: red" @click="deletePdf(scope.row)">删除</div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="page.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize"
                :total="page.total" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
        <!-- 弹窗, 新增 / 修改 -->

        <tags-select v-if="tagsSelectVisible" :limit="5" ref="tagsSelect" @refreshTagsArr="refreshTagsSelect"></tags-select>
    </div>
</template>

<script>
import JSzip from 'jszip';
import { saveAs } from 'file-saver';

export default {
    data() {
        return {
            theData: null, // 保存上次点击查询的请求条件

            dataList: [],
            dataListLoading: false,
            exportDisabled: false,
            importDisabled: false,
            tagsSelectVisible: false,
            updateBalanceVisible: false,
            updateCouponVisible: false,
            dataListSelections: [],
            addOrUpdateVisible: false,
            updateGrowthVisible: false,
            updateScoreVisible: false,
            updateTagsVisible: false,
            importUserVisible: false,
            createDateRange: [], // 时间范围
            resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
            dynamicTags: [],
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            searchForm: {
                printChannel: 'Lightning',
                orderNumber: undefined,
                startTime: undefined, // 起始时间
                endTime: undefined, // 结束时间,
                pdfName: null,
            },
            levelTypes: [
                {
                    label: this.$i18n.t('user.ordinaryMember'),
                    value: 0
                }, {
                    label: this.$i18n.t('user.paidMembership'),
                    value: 1
                }
            ],
            status: [
                {
                    label: this.$i18n.t('publics.disable'),
                    value: 0
                }, {
                    label: this.$i18n.t('publics.normal'),
                    value: 1
                }
            ]
        }
    },
    components: {
    },
    mounted() {
        this.getDataList(this.page)
    },
    methods: {
      deletePdf(pdf){
        this.$confirm("确定要删除PDF文件吗"+ '?', "提示", {
          confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
          cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/printOrderPdf/printOrderPdf/' + pdf.orderPdfId),
            method: 'delete',
            data: this.$http.adornData({})
          }).then(({ data }) => {
            this.$message({
              message: this.$i18n.t('publics.operation'),
              type: 'success',
              duration: 200,
            });
            this.getDataList(this.page)
          })
        }).catch(() => { })
      },
        downLoadPDF(pdf) {
            let randomStr = Math.floor(Math.random() * 100000).toString();
            this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + "?a=" + randomStr).then(data => {
                saveAs(data, pdf.pdfName)
            })
        },
        getPdfFile(url) {
            return new Promise((resolve, reject) => {
                let xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", url, true);
                xmlhttp.responseType = "blob";
                xmlhttp.onload = function () {
                    if (this.status == 200) {
                        resolve(this.response);
                    } else {
                        reject(this.status);
                    }
                }
                xmlhttp.send();
            });
        },
        getAllNeed() {
            if (!this.theData) {
                this.theData = JSON.parse(JSON.stringify(this.searchForm))
            }
            this.$http({
                url: this.$http.adornUrl('/printOrderPdf/printOrderPdf/page'),
                method: 'get',
                params: this.$http.adornParams(
                    Object.assign(
                        {
                            current: 1,
                            size: 9999
                        },
                        this.theData
                    )
                )
            }).then(({ data }) => {
                console.log(data.records)
                let pdfList = data.records;
                // const arr = [{fileDownUrl:'地址', fileDownName:'文件名'}] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
                const zip = new JSzip()
                const cache = {}
                const promises = []
                pdfList.forEach((pdf, j) => {
                    let randomStr = Math.floor(Math.random() * 100000).toString();
                    const promise = this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + "?a=" + randomStr).then(data => {
                        // 下载文件, 并存成blob对象
                        const fileName = pdf.pdfFolderName + "/" + pdf.pdfName; // 获取文件名，一定要包含文件的后缀名(因为重复的文件名只会下载一个，故需要加入下标 不同名)
                        // zip.folder(pdf.pdfFolderName).file(pdf.pdfName, data);
                        zip.file(pdf.pdfName, data);
                        cache[fileName] = data
                    })
                    promises.push(promise)
                });
                Promise.all(promises).then(() => {
                    zip.generateAsync({ type: "blob" }).then(content => {
                        // 生成二进制流   然后保存文件（如果这个下载不了 也可以将下方这一行换成a标签下载逻辑）
                        saveAs(content, "批量下载PDF压缩包.zip") // 利用file-saver保存文件  自定义文件名
                        // this.wavePrintOrderPdfDownloadLoading = false;
                    })
                })
            });
        },
        downLoadZIP() {
            if (!!this.searchForm.startTime && !!this.searchForm.endTime) {
                if ((Date.parse(new Date(this.searchForm.endTime).toString()) - Date.parse(new Date(this.searchForm.startTime).toString())) / 1000 / 60 / 60 <= 24) {
                    this.getAllNeed()
                } else {
                    this.$message({
                        message: '批量下载ZIP范围最大为24小时',
                        type: 'warning'
                    });
                }
            } else {
                this.$message({
                    message: '请先选择创建时间，范围最大为24小时',
                    type: 'warning'
                });
            }
        },

        // 获取数据列表  /admin/user/page
        getDataList(page, newData = false) {
            if (newData || !this.theData) {
                this.theData = JSON.parse(JSON.stringify(this.searchForm))
            }
            this.dataListLoading = true

            this.$http({
                url: this.$http.adornUrl('/printOrderPdf/printOrderPdf/page'),
                method: 'get',
                params: this.$http.adornParams(
                    Object.assign(
                        {
                            current: page == null ? this.page.currentPage : page.currentPage,
                            size: page == null ? this.page.pageSize : page.pageSize
                        },
                        this.theData
                    )
                )
            }).then(({ data }) => {
                this.dataList = data.records
                this.page.total = data.total
                this.dataListLoading = false
            })
        },
        // 新增 / 修改
        addOrUpdateHandle(id) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id)
            })
        },
        // 条件查询 JSON.stringify(arr)
        searchChange(newData = false) {
            this.page.currentPage = 1
            this.getDataList(this.page, newData)
        },
        handleSizeChange(val) {
            this.page.pageSize = val
            this.getDataList(this.page)
        },
        handleCurrentChange(val) {
            this.page.currentPage = val
            this.getDataList(this.page)
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
            this.searchForm.startTime = undefined
            this.searchForm.endTime = undefined
            this.searchForm.orderNumber = undefined
            this.createDateRange = []
            this.theData = null
            this.getDataList(this.page)
        },
        createTimeChange() {
            if (!this.createDateRange || this.createDateRange.length === 0) {
                this.searchForm.startTime = undefined
                this.searchForm.endTime = undefined
            } else {
                this.searchForm.startTime = this.createDateRange[0]
                this.searchForm.endTime = this.createDateRange[1]
            }
            this.searchChange(true)
        },
        // 多选变化
        selectionChange(val) {
            this.dataListSelections = val
        },
        updateGrowth(id) {
            if (this.dataListSelections.length <= 0) {
                return
            }
            var ids = id ? [id] : this.dataListSelections.map(item => {
                return item.userId
            })
            // console.log(ids)
            this.updateGrowthVisible = true
            this.$nextTick(() => {
                this.$refs.updateGrowth.init(ids)
            })
        },
        // 修改成长值
        updateScore(id) {
            if (this.dataListSelections.length <= 0) {
                return
            }
            var ids = id ? [id] : this.dataListSelections.map(item => {
                return item.userId
            })
            // console.log(ids)
            this.updateScoreVisible = true
            this.$nextTick(() => {
                this.$refs.updateScore.init(ids)
            })
        },
        /**
         * 导出单品
         */
        exportUser() {
            this.exportDisabled = true
            this.$http({
                url: this.$http.adornUrl('/admin/user/exportUser'),
                method: 'get',
                params: this.$http.adornParams(this.searchForm),
                responseType: 'blob' // 解决文件下载乱码问题
            }).then(({ data }) => {
                this.exportDisabled = false
                var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
                const fileName = this.$i18n.t('user.userInformationForm')
                const elink = document.createElement('a')
                if ('download' in elink) { // 非IE下载
                    elink.download = fileName
                    elink.style.display = 'none'
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(elink.href) // 释放URL 对象
                    document.body.removeChild(elink)
                } else { // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.mod-user {
    .tips .text {
        color: #FF0000;
    }
}

.TagS {
    margin-right: 10px !important;
}
</style>
