<template>
    <div>
        <BaseTable :columns='columns' :condition='condition' :queryFunction='queryFunction' ref="table"
            paginationSize="mini"
            :paginationText="{ currentPage: 'pageCurrent', total: 'countTotal', totalPage: 'pageCount', data: 'orderList' }"
            size="small" :span="12">
            <template slot="append-btn">
                <el-button type="success" size="small" @click="exportFunction">导出</el-button>
            </template>
        </BaseTable>
    </div>
</template>

<script>
import * as tableConfig from '@/components/base-table/config.js'
import BaseTable from "@/components/base-table/base-table.vue"
import moment from "moment";
export default {
    data() {
        return {
            columns: tableConfig.liveroomProductJumpRecord.columns,
            condition: tableConfig.liveroomProductJumpRecord.condition,
            queryParam: {},
            total: 0,
            queryFunction: params => new Promise((resolve, reject) => {
                let url = '/room/records'
                let formatParams = {
                    "roomId": parseInt(this.$route.params.id), //直播间 ID
                    "page": params.pageCurrent, //当前第几页
                    "limit": 10 //页面的大小
                }
                if (params.query.time) {
                    url = '/room/search'
                    formatParams.start = params.query.time[0]
                    formatParams.end = params.query.time[1]
                }
                return this.$http({
                    url,
                    method: 'post',
                    data: formatParams,
                    params: formatParams
                }).then(
                    ({ data }) => {
                        const formatData = {
                            pageCurrent: params.pageCurrent,
                            countTotal: data.total,
                            pageCount: Math.ceil(data.total / 10),
                            orderList: data.maiDiansList || []
                        }
                        url == '/room/records' && (this.total = data.total)
                        resolve(formatData)
                    }
                ).catch(e => reject(e))
            }),
        }
    },
    components: { BaseTable, },
    mounted() {
    },
    methods: {
        exportFunction() {
            console.log(this.$route);
            let formatParams = {
                "roomId": parseInt(this.$route.params.id), //直播间 ID
                "page": 1, //当前第几页
                "limit": this.total //页面的大小
            }
            this.$http({
                url: '/room/records',
                method: 'post',
                data: formatParams,
                params: formatParams
            }).then(
                ({ data }) => {
                    this.exportToCSVFile(data.maiDiansList)
                }
            )
        },

        exportToCSVFile(list) {
            let header = '用户,商品名称,商品链接,点击时间\n';
            let datas = list.map(ele => {
                return `${ele.phone},${ele.name},${ele.linkInfo},${moment(ele.createAt).format("yyyy-MM-DD HH:mm:ss")}\n`;
            });
            let dataStrs = [header, ...datas].join('');
            // 创建一个 Blob 对象
            const blob = new Blob(['\uFEFF' + dataStrs], {
                type: 'text/plain;charset=utf-8',
            });
            // 创建一个 a 标签
            const link = document.createElement("a");
            // 一个 URL，可以是任意协议的，不只是 HTTP 协议
            // 这里创建了一个 Blob URL
            // blob:http://localhost:1234/9b3be48e-9948-496d-8a2b-18d437eb46e0
            link.href = URL.createObjectURL(blob);
            console.log(link.href);

            // 此属性表示用户下载文件而不是进行导航到 URL，这里指的为文件名
            link.download = `商品跳转记录-${this.$route.query.title}直播间（苏州掌银客户专享）.csv`;
            link.click();
            // 需要释放 URL
            URL.revokeObjectURL(link.href);
        },
        exportList(list, title) {
            //表格表头,导出表头
            let tableHeader = [['#', '资产编号', '资产名称', '资产类别', '资产型号', "资产单价", "资产金额",
                "生产厂家", "生产日期", "购买日期", "购买人", "状态", "库存数量"]]
            list.forEach((item, index) => {
                let rowData = []
                //导出内容的字段
                rowData = [
                    index + 1,
                    item.zcbh,
                    item.zcmc,
                    item.name,
                    item.zcxh,
                    item.zcdj,
                    item.zcje,
                    item.sccj,
                    currencyFormatDate(item.scrq),
                    currencyFormatDate(item.gmrq),
                    item.gmr,
                    item.sts,
                    item.kcsl,
                ]
                tableHeader.push(rowData)
            })
            let wb = XLSX.utils.book_new()
            let ws = XLSX.utils.aoa_to_sheet(tableHeader)
            XLSX.utils.book_append_sheet(wb, ws, '资产设备基本信息') // 工作簿名称
            XLSX.writeFile(wb, '商品跳转记录-老字号直播间（苏州掌银客户专享）.xlsx') // 保存的文件名
        }
    }
}
</script>

<style></style>