<script setup>
import { ref, onMounted } from 'vue';
import request, {download} from "@/utils/request.js";
import { ElTable, ElTableColumn, ElPagination, ElButton, ElMessageBox, ElMessage, ElDialog } from 'element-plus';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const pageNum = ref(1);
const multipleSelection = ref([]);
const dialogVisible = ref(false);
const fileList = ref([]);

const getList = async () => {
  const condition = [];
  condition.push({
    column: 'create_time',
    type: 'orderByDesc'
  })
  const res = await request.get('/xcr-ow-self-reporting/findByPage', {
    params: {
      pageSize: pageSize.value,
      pageNum: pageNum.value,
      conditionJson: encodeURIComponent(JSON.stringify(condition))
    }
  });
  // 格式化 createTime
  tableData.value = res.records.map(record => ({
    ...record,
    createTime: formatDateTime(record.createTime)
  }));
  total.value = res.total;
};

const formatDateTime = (dateTimeString) => {
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  getList();
};

const handleCurrentChange = (newPageNum) => {
  pageNum.value = newPageNum;
  getList();
};

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const res = await request.post('/xcr-ow-self-reporting/delete', [id]);
    if (res.code === 200) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    ElMessage.error('取消删除');
  }
};

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const ids = multipleSelection.value.map(row => row.id);
    const res = await request.post('/xcr-ow-self-reporting/delete', ids);
    if (res.code === 200) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    ElMessage.error('取消删除');
  }
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const showFileList = (files) => {
  fileList.value = files;
  dialogVisible.value = true;
};

const handleDownload = async (filePath,fileName)=>{
  download('/xcrFile/downloadFile',{filePath},fileName)
}

onMounted(() => {
  getList();
});
</script>

<template>
  <div class="p-10px">
    <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="complainantIdNumber" label="投诉人身份证号" width="180"/>
      <el-table-column prop="contactInformation" label="联系方式" width="180"/>
      <el-table-column prop="contacts" label="联系人" width="180"/>
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column prop="enterpriseName" label="企业名称" width="180"/>
      <el-table-column prop="unifiedSocialCreditCode" label="统一社会信用代码" width="180"/>
      <el-table-column label="文件" width="180">
        <template #default="scope">
          <el-button v-show="scope.row.files.length > 0" type="primary" @click="showFileList(scope.row.files)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />
    <!-- 文件列表对话框 -->
    <el-dialog v-model="dialogVisible" title="文件列表" width="50%">
      <ul>
        <li v-for="(file, index) in fileList" :key="index" class="flex w-full justify-between">
          <div>{{ file.fileOriginalName }}</div>
          <div class="pr-20px"><el-button size="small" @click="handleDownload(file.fileUrl,file.fileOriginalName)">下载</el-button></div>
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
