<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="6">
            <el-form-item label="联系人姓名：" prop="table_name" label-width="auto">
              <el-input v-model="creator_name" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>
          </el-col>
          <!-- 联系电话 -->
          <el-col :span="6">
            <el-form-item label="联系电话：" prop="table_phone" label-width="auto">
              <el-input v-model="creator_phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <!-- 选择填报人 -->
          <el-col :span="6">
            <el-form-item label="选择填报人：" prop="table_name" label-width="auto">
              <el-select v-model="selectedReporter" placeholder="请选择填报人">
                <el-option v-for="reporter in reporters" :key="reporter.id" :label="reporter.name" :value="reporter.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 截止时间 -->
          <el-col :span="6">
            <el-form-item label="截止时间：" prop="release_time">
              <el-date-picker v-model="selectedTime" type="date" placeholder="选择截止时间" @change="handleTimeChange" />
              <span class="label">前报送该表</span>
            </el-form-item>
          </el-col>
          <!-- 操作按钮 -->
          <el-col :span="6">
            <el-input v-model="table_name" placeholder="请输入表名"></el-input>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleReport()"> 智能识别 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleSaveTemporarily">暂存</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleSave()"> 发布 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" @click="handleReturn()"> 返回 </el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-row :gutter="20" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleImportExcel">导入Excel文件</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleNewTemplate">空白模板</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleReload">重新加载</el-button>
        </el-col>
      </el-row>
      <!-- 表格组件 -->
      <el-col :lg="30" :xs="24">
        <el-table :data="field_names" border>
          <el-table-column v-for="header in editableHeaders" :key="header" :label="header" :prop="header">
            <template #default="{ row, $index }">
              <el-input v-model="row[header]" @blur="saveEdit($index, header, row[header])" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElButton, ElCol, ElDatePicker, ElFormItem, ElInput, ElOption, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import * as XLSX from 'xlsx';
import { fillingAdd } from '@/api/dataFilling/fillingManage';

const emits = defineEmits(['close']);
const detailData = ref({
  title: '表单数据',
  start: '2024-10-15 17:02:22',
  end: '2024-10-15 18:00:00'
});

const field_names = ref([]);
const editableHeaders = ref([]);
const creator_name = ref('');
const creator_phone = ref('');
const selectedReporter = ref(null);
const reporters = ref([]); // 确保这个数组被正确初始化
const selectedTime = ref(null);
const table_name = ref('');
const data_table_name = ref(''); // 假设这是另一个输入字段，需要在模板中添加对应的输入框
const status = ref(0); // 假设这是一个选择器或输入框
const issued_status = ref(0); // 假设这是一个选择器或输入框
const period_type = ref(''); // 假设这是一个输入框或选择器
const creator_id = ref(null); // 这通常是用户ID，可能需要从登录信息中获取

// 初始化表格数据
onMounted(() => {});

function saveEdit(rowIndex, header, value) {
  field_names.value[rowIndex][header] = value;
  localStorage.setItem('field_names', JSON.stringify(field_names.value));
}

const handleNewTemplate = () => {
  // 创建一个新的10x10的数组，每个元素是一个对象，对象的键为列名，值为空字符串
  const newHeaders = Array.from({ length: 10 }, (_, index) => `列${String.fromCharCode(65 + index)}`); // 生成列名
  field_names.value = Array.from({ length: 10 }, (v, k) => {
    const obj = {
      序号: k + 1
    };
    newHeaders.forEach((header) => {
      obj[header] = '';
    });
    return obj;
  });

  // 更新editableHeaders
  editableHeaders.value = ['序号', ...newHeaders];

  alert('空白模板已创建');
};

const handleImportExcel = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx';
  input.onchange = async (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onload = async (e) => {
      const data = e.target.result;
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      field_names.value = XLSX.utils.sheet_to_json(worksheet);
      alert('Excel文件已导入');
    };
    reader.readAsArrayBuffer(file);
  };
  input.click();
};

const handleReload = () => {
  field_names.value = [];
  alert('表格已清空');
};

const handleSaveTemporarily = () => {
  localStorage.setItem('field_names', JSON.stringify(field_names.value));
  alert('数据已暂存');
};

const handleReport = () => console.log('上报');

const handleSave = async () => {
  // 构造要发送的数据对象
  const data = {
    table_name: table_name.value,
    data_table_name: data_table_name.value,
    start_time: selectedTime.value ? selectedTime.value.startOfDay.format() : '',
    end_time: selectedTime.value ? selectedTime.value.endOfDay.format() : '',
    status: status.value,
    issued_status: issued_status.value,
    period_type: period_type.value,
    creator_name: creator_name.value,
    creator_id: creator_id.value,
    creator_phone: creator_phone.value,
    field_names: field_names.value,
    user_ids: [] // 这个需要根据实际情况来填充
  };

  // 保存本地状态
  localStorage.setItem('field_names', JSON.stringify(field_names.value));
  try {
    // 调用fillingAdd接口，传递data作为请求体
    const response = await fillingAdd(data);
    if (response && response.success) {
      alert('数据已成功保存');
    } else {
      alert('数据保存失败');
    }
  } catch (error) {
    console.error('保存数据失败:', error);
    alert('数据保存失败');
  }
};

const handleReturn = () => {
  emits('close');
};
</script>

<style scoped>
.app-container {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
.report-period {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}
.editable-span {
  cursor: pointer;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.editable-span[contenteditable='true'] {
  white-space: normal;
  outline: none; /* 移除编辑时的焦点边框 */
}
.editable-span[contenteditable='true']:empty::before {
  content: attr(data-placeholder); /* 可选：为空时显示占位符 */
  color: #999;
}
.editable-header {
  cursor: pointer;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.editable-header[contenteditable='true'] {
  white-space: normal;
  outline: none; /* 移除编辑时的焦点边框 */
}
.editable-header[contenteditable='true']:empty::before {
  content: attr(data-placeholder); /* 可选：为空时显示占位符 */
  color: #999;
}
</style>
