<template>
  <div class="bodyclass">
    <el-select v-model="nowModel"
               placeholder="选择机型"
               style="width: 150px;">
      <el-option v-for="item in models"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value" />
    </el-select>
    <span>&nbsp;</span>
    <el-button type="info" @click="handleImportClick" v-show="nowModel">导入Excel</el-button>
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" accept=".xlsx, .xls" />
    <span>&nbsp;</span>
    <el-tag type="success" closable @close="tagClose(tag)" v-if="fileName" size="large">
      {{ fileName }}
    </el-tag>
    <span>&nbsp;</span>
    <el-button type="danger" @click="" v-show="fileDate.length > 0">保存到数据库</el-button>
  </div>
  <div style="min-height: 85vh; margin-top: 3px;">
    <el-table :data="fileDate" style="width: 100%">
      <el-table-column v-for="header in headers"
                       :key="header"
                       :prop="header"
                       :label="header"
                       width="180">
        <template #header>
          <span :style="{ color: !tableNames.includes(header) ? 'red' : 'green' }">
            {{ header }}
          </span>
        </template>
        <template #default="scope">
          <span :style="{ color: !tableNames.includes(header) ? 'red' : 'green' }">
            {{ scope.row[header] }}
          </span>
        </template>
      </el-table-column>
    </el-table>
  </div>

</template>

<script setup>
  import { ref, inject, onMounted } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import * as XLSX from 'xlsx';
  import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  const $http = inject('$http')

  const value = ref('')
  const models = ref([
    {
      value: 'models1',
      label: 'models1',
    },
    {
      value: 'models2',
      label: 'models2',
    },
    {
      value: 'models3',
      label: 'models3',
    }
  ])

  const nowModel = ref('')
  const fileInput = ref(null)
  const headers = ref([])
  const fileDate = ref([])
  const fileName = ref('')

  const handleImportClick = () => {
    fileInput.value.click()
  }

  const handleFileChange = async (e) => {
    const file = e.target.files[0]
    if (!file) return

    try {
      // 读取Excel文件
      const data = await file.arrayBuffer()
      const workbook = XLSX.read(data, { type: 'array' })
      const worksheet = workbook.Sheets[workbook.SheetNames[0]]
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      headers.value = Object.keys(jsonData[0])
      fileDate.value = jsonData
      // 这里可以处理解析后的数据，例如：
      // 1. 发送到服务器
      //await $http.post('/api/upload', jsonData)

      // 2. 或者更新models数据（示例）
      // models.value = jsonData.map(item => ({
      //   value: item.模型ID,
      //   label: item.模型名称
      // }))

      fileName.value = file.name
      console.log('导入成功:', jsonData)
      Toast('文件导入成功')
    } catch (error) {
      console.error('导入失败:', error)
      Toast('文件导入失败')
    } finally {
      e.target.value = '' // 清空选择允许重复上传
    }
  }

  const tableNames = ref([])

  const tagClose = () => {
    fileDate.value = []
    fileName.value = ''
  }


  // 获取数据库表
  const getTable = () => {
    let requestBody = {
      key: "getTable",
      CmdType: "sys",
      DBQueryData: [
        {
          key: "@DBName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        },
        {
          key: "@TBName",
          value: "tbl_importinfo",
          valueType: "string",
        }
      ]
    }

    $http.post('DataHandle/R_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          tableNames.value = []
          rs.data.response.forEach((item, index) => {
            tableNames.value.push(item.name)
          });

          //console.log(tableNames.value)
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
  }

  // 初始化加载数据
  onMounted(() => {
    getTable()
  });
</script>

<style scoped>
  @media (min-width: 1024px) {
    .bodyclass {
      margin-top: 5px
    }
  }
</style>
