<template>
    <div>
        <a-button type="primary" style="margin: 10px 0;" :loading="state.exportLoading" @click="onExport">
            导出 Excel </a-button>

            <a-button type="primary" style="margin: 10px 10px;"  @click="onPrint">
            复制 url Json </a-button>
    </div>
</template>
<script setup>
import { defineProps, reactive, watch } from 'vue';
import { exportExcelFunc } from './exportExcel';
const props = defineProps({
    tableData: [],
    userId: ''
})

const state = reactive({
    exportLoading: false,
    dataSource: [],
    userId: ''
})

const onExport = () => {
    console.log('export')
    if (!state.dataSource || state.dataSource.length === 0) {
        window.alert('表格数据为空')
        return
    }
    state.exportLoading = true
    exportExcelFunc(state.dataSource, state.userId).then(res => {
        state.exportLoading = false
        console.log('res', res)
    }).catch(r => {
        state.exportLoading = false
        console.log('r', r)
    })
}
watch(() => props.tableData,
    (val) => {
        state.dataSource = val
    }, {
    deep: true,
    immediate: true
})
watch(() => props.userId,
    (val) => {
        state.userId = val
    }, {
    deep: true,
    immediate: true
})
const copyContent = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      console.log('Content copied to clipboard');
      window.alert('复制成功！')
    } catch (err) {
      console.error('Failed to copy: ', err);
       window.alert(JSON.stringify(err))
    }
  }
const onPrint=()=>{
    const json={articleInfo:null}
    console.log('state.dataSource',state.dataSource)
    const urlArray=state.dataSource.map(item=>{
        return {
            url:item.url
        }
    })
    json.articleInfo=urlArray
    const text=JSON.stringify(json,null,'\t')
    console.log('json text',text)
    copyContent(text)
}
</script>