<template>
  <div class="app-container p-2">
    <el-row :gutter="20">
      <el-col :lg="30" :xs="24" style="">
        <el-row :span="24" :gutter="10">
          <el-col :span="18" label="任务名称">
            <h2 v-if="detailData.title" key="business" style="font-weight: bolder">{{ detailData.title }}</h2>
            <p class="report-period">【填报周期】：{{ detailData.start }} 至 {{ detailData.end }}</p>
          </el-col>
          <el-col v-if="props.collectionStatus === '0'" :span="1.5">
            <el-button type="primary" @click="handleWrite()"> 收取 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" @click="handleReturn()"> 返回 </el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-col :lg="30" :xs="24">
<!--        <el-table :data="tableData" border>-->
<!--          <el-table-column v-for="header in editableHeaders" :key="header.prop" :label="header.label" :prop="header.prop">-->
<!--            <template #header="{ column }">-->
<!--              <span class="editable-header" v-text="column.label"></span>-->
<!--            </template>-->
<!--            <template #default="{ row, $index }">-->
<!--              <span class="editable-span" v-text="row[header.prop]"></span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
        <div :style="{ height: tableHeight + 'px' }">
          <hot-table ref="wrapper" :data="tableData" :settings="hotSettings" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElTable, ElButton, ElCol, ElRow, ElTableColumn, ElMessageBox } from 'element-plus';
import * as XLSX from 'xlsx';
import { fillDetail, collectList } from '@/api/dataFilling/fileManagement';
import { HotTable } from '@handsontable/vue3';
import 'handsontable/languages';
import 'handsontable/dist/handsontable.full.css';
import { registerAllModules } from 'handsontable/registry';
registerAllModules();

const emits = defineEmits(['close', 'refresh']);
const props = defineProps({
  eventId: String,
  tableName: String,
  collectionStatus: String
});
//初始化表头和表格数据
const editableHeaders = ref([]);
const tableData = ref([]);
const detailData = ref({
  title: '',
  start: '',
  end: ''
});
let tableHeight = window.innerHeight - 230
let wrapper = ref();
onMounted(() => {
  fetchFillDetail();
});
const editableHeadersList = ref([]);
const fetchFillDetail = async () => {
  try {
    const res = await fillDetail({ report_id: props.eventId });
    // 动态设置表头
    editableHeaders.value = res.columns;
    // 转换表格数据格式以匹配表头

    detailData.value.start = res.start_time;
    detailData.value.end = res.end_time;


    editableHeaders.value.forEach((header) => {
      editableHeadersList.value.push(header.label)
    })
    let arr1 = []
    // tableData.value = response.tableData;
    //如果tableData是空就用下满这段，tableData有数据就用tableData的内容
    if (!res.rows || res.rows.length === 0) {
      editableHeadersList.value.forEach((item) => {
        arr1.push('');
      })
      tableData.value = [arr1];
      wrapper.value.hotInstance.loadData([arr1]);
    } else {
      tableData.value = res.rows.map((row) => {
        const formattedRow = {};
        editableHeaders.value.forEach((header) => {
          formattedRow[header.prop] = row[header.prop];
        });
        return formattedRow;
      });
      wrapper.value.hotInstance.loadData(tableData.value);
    }
    wrapper.value.hotInstance.loadData(tableData.value);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// //收取
// const handleWrite = () => {
//   if (props.eventId && props.eventId !== '') {
//     const data = {
//       report_id: props.eventId,
//       creator_id: 3,
//       new_status: 2
//     };
//     collectList(data)
//       .then((response) => {
//         if (response.code === 200) {
//           console.log(response.msg);
//         } else {
//           console.error('更新失败', response.msg);
//         }
//       })
//       .catch((error) => {
//         console.error('请求失败', error);
//       });
//   }
// };
// 收取
const handleWrite = () => {
  ElMessageBox.confirm('收取后，表格不可再填报，确认是否收取？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (props.eventId && props.eventId !== '') {
        const data = {
          report_id: props.eventId,
          creator_id: 3,
          new_status: 2
        };
        collectList(data)
          .then((response) => {
            if (response.code === 200) {
              console.log(response.msg);
              // 更新 collectionStatus 为 '2'（已收取）
              emits('update:collectionStatus', '2');
            } else {
              console.error('更新失败', response.msg);
            }
          })
          .catch((error) => {
            console.error('请求失败', error);
          });
      }
    })
    .catch(() => {
      // 用户点击了取消按钮
      console.log('取消收取');
    });
  emits('refresh');
};
const handleReturn = () => {
  emits('close');
};
const hotSettings = reactive({
  language: 'zh-CN',
  readOnly: true,
  colHeaders: editableHeadersList,
  rowHeaders: true,
  autoColumnSize: true,
  width: '100%', // auto  or  100%
  height: '100%', // auto  or  100%
  licenseKey: 'non-commercial-and-evaluation', // 隐藏版权文字
  colWidths: 129, // 默认单元格宽度
  rowHeights: 28, // 默认单元格高度
  wordWrap: true, // 单元格文字是否换行展示
  contextMenu: {
    // 自定义右键菜单
    items: {
      'row_above': {
        name: '向上插一行'
      },
      'row_below': {
        name: '向下插一行'
      },
      'col_left': {
        name: '向左插一列'
      },
      'col_right': {
        name: '向右插一列'
      },
      'hsep1': '---------', // 分隔线
      'remove_row': {
        name: '删除当前行'
      },
      'remove_col': {
        name: '删除当前列'
      },
      'clear_column': {
        name: '清空当前列'
      },
      'hsep2': '---------', // 必须和上次的变量名不一样
      'undo': {
        name: '撤销'
      },
      'cut': {
        name: '剪切'
      },
      'copy': {
        name: '复制'
      },
      'alignment': {
        name: '对齐'
      },
      'hsep3': '---------',
      'commentsAddEdit': {
        // 必须开启 comments: true
        name: '添加备注'
      },
      'commentsRemove': {
        // 必须开启 comments: true
        name: '删除备注'
      },
      'freeze_column': {
        // 必须开启 manualColumnFreeze: true
        name: '固定列'
      },
      'unfreeze_column': {
        // 必须开启 manualColumnFreeze: true
        name: '取消固定列'
      }
    }
  }
});
</script>

<style scoped>
.app-container {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
.report-period {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}
.editable-span {
  cursor: default;
}
.editable-header {
  cursor: default;
}
</style>
