<script lang="ts" setup>
import { h, onMounted, ref, watch } from 'vue';
import type { DataTableColumns, DataTableRowKey, FormInst, UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui';
import {
  NButton,
  NCard,
  NDataTable,
  NDialog,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NPagination,
  NRadio,
  NSpace,
  NSpin,
  useDialog,
  useMessage
} from 'naive-ui';
import { roleRules } from '@/rules/rules';
import { deleteModelApi, getModelPageApi, postModelApi, postModeluploadApi } from '@/api';
import { render } from 'nprogress';

const message = useMessage();
const fileList = ref<[]>([])
const uploadIdentification = ref('')
// 常量和响应式数据
const tableData = ref([]);
const updata = [
  {
    label: '无人机航测',
    value: '1',
  },
  {
    label: '其他',
    value: '2'
  },
]
const updata1 = [
  {
    label: 'B3DM',
    value: '1',
  },
  {
    label: '其他',
    value: '4'
  },
]
const createModal = ref(false);
const ids = ref<DataTableRowKey[]>([]);
const pageSizes = ref([10, 20, 50, 100]);
const show = ref(false);
const title = ref('模型上传');
const range = ref<any>();
const dataMessage = ref('模型上传中，请稍后')
const show01 = ref(true)
const isShow01 = ref(false)
const state01 = ref<any>("warning")

const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 10
});
// 数据绑定
const formData = ref({
  id: '',
  informationName: '',
  filePath: '',
  fileSize: '',
  fileType: '',
  type: ''
});
const serarchData = ref({
  pageNum: pageData.value.pageNum,
  pageSize: pageData.value.pageSize,
})

// 表格列配置
const tableColumn = [
  {
    title: '文件名称',
    key: 'informationName',
    align: 'center',
    minWidth: 200
  },
  {
    title: '上传类型',
    key: 'type',
    align: 'center',
    minWidth: 120,
    render(row: any) {
      let text = ''
      if (row.fileType === 1) {
        text = '无人机航测'
      } else if (row.fileType === 2) {
        text = '其他'
      } 
      return h('span', text)
    }
  },
  {
    title: '上传时间',
    key: 'createTime',
    align: 'center',
    minWidth: 120,
  },
  {
    title: '文件类型',
    key: 'fileType',
    align: 'center',
    minWidth: 120,
    render(row: any) {
      let text = ''
      if (row.type === 1) {
        text = 'B3DM'
      } else if (row.type === 2) {
        text = '其他'
      }
      return h('span', text)
    }
  },
  {
    title: '文件大小',
    key: 'fileSize',
    align: 'center',
    minWidth: 120
  },
  {
    title: '创建日期',
    key: 'createTime',
    align: 'center',
    minWidth: 180
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    minWidth: 120,
    render(row: any) {
      // 改用Vue推荐的方式创建元素
      return h(NSpace, { justify: 'center' }, [
        h(
          NButton,
          {
            size: 'small',
            style: {
              color: '#eee',
              backgroundColor: '#f16255',
              borderColor: '#f16255',
              borderRadius: '4px',
              padding: '4px 12px'
            },
            onClick: () => handleDelete(row)
          },
          [
            h('img', {
              src: '/src/assets/delete.png',
              alt: '删除',
              style: {
                width: '10px',
                height: '10px',
                marginRight: '5px'
              }
            }),
            '删除'
          ]
        )
      ]);
    }
  }
];

// 添加表单校验相关的引用和方法
const formRef = ref<InstanceType<typeof NForm>>();
  
function handleSubmit() {
  createModal.value = false;
  show01.value = false;
  if (!formRef.value) return;
  formRef.value.validate(async errors => {
    if (!errors) {
      let res = await postModelApi(formData.value);
      search();
      if(res.data.code != 200) {
        message.error(res.data.msg)
      }
      if(dataMessage.value = '文件上传成功') {
        message.create('')
      }
    } else {
      console.log('表单校验失败', errors);
    }
  });
}

function handleCheck(rowKeys: DataTableRowKey[]) {
  ids.value = rowKeys;
}

const dialog = useDialog();
function handleDelete(row: any) {
  dialog.create({
    title: '提示',
    content: '确定删除数据？',
    positiveText: '确定',
    negativeText: '取消',
    positiveButtonProps: {
      type: 'primary' // 设置确定按钮为蓝色
    },
    showIcon: false, // 去掉感叹号图标
    onPositiveClick: async () => {
      // 用户确认删除后执行删除操作
      let res = await deleteModelApi(row.id);
      if(res.data.code == 200){
        search()
        message.success('删除成功')
      }else{
        message.error(res.data.msg)
      }
    }
  });
}
//  头部新增
function handleAdd() {
  title.value = '模型上传'
  // 重置表单数据
  formData.value = {
    id: '',
    informationName: '',
    filePath: '',
    fileSize: '',
    fileType: '',
    type: ''
  };
  isShow01.value = false;
  show01.value = false;
  createModal.value = true;
}

async function search() {
  let res = await getModelPageApi(serarchData.value);
  if(res.data.code == 200) {
    tableData.value = res.data.data.records;
    pageData.value = {
      pageNum: res.data.data.page,
      pageSize: res.data.data.pageSize,
      total: Number(res.data.data.total)
    } 
  } else {
    message.error(res.msg);
  }
}

function handlePage() {
  serarchData.value.pageNum = pageData.value.pageNum;
  search();
}

function handlePageSize() {
  serarchData.value.pageSize = pageData.value.pageSize;
  pageData.value.pageNum = 1;
  serarchData.value.pageNum = 1;
  search();
}

function beforeUpload(file: any) {
  const allowedTypes = [
    'application/zip',
    'application/x-rar',
    'application/x-zip-compressed',
    'application/x-7z-compressed',
    'application/x-gtar',
    'application/x-bzip',
    'application/x-bzip2',
    'application/x-apple-diskimage',
    'application/java-archive',
    'application/vnd.android.package-archive',
    'application/x-msdownload',
    'application/x-xz',
    'image/tiff'
  ];

  // 获取文件的MIME类型
  const mimeType = file.file.type;

  // 检查文件类型是否被允许
  if (!allowedTypes.includes(mimeType)) {
    message.error("只能上传压缩文件（如.zip, .rar, .7z等），请重新上传");
    return false; // 返回false取消上传
  } else {
    if (uploadIdentification.value == 'model') {
      isShow01.value = true
    }
  }
  return true; // 返回true允许上传
}

function finishUpload(event: any) {
  const res = JSON.parse(event.event.target.response)
  
  if (res.code == 200) {
    state01.value = "success";
    show01.value = false;
    dataMessage.value = '文件上传成功';
    formData.value.filePath = res.data.filePath
    formData.value.fileSize = res.data.fileSize
  } else {
    errorUpload()
  }
}

function errorUpload() {
  state01.value = 'error'
  show01.value = false
  dataMessage.value = '文件上传失败'
}

function updataType(e:any) {
  formData.value.type = e;
}

function updataType1(e:any) {
  formData.value.fileType = e;
}

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

<template>
  <div id="DepartmentPage">
    <NModal v-model:show="createModal">
      <NCard :title="title" style="width: 600px" @close="createModal = false">
        <hr />
        <NForm ref="formRef" label-placement="left" label-width="auto" :rules="roleRules" :model="formData"
          style="margin-left: 20px; margin-top: 20px">
          <NFormItem label="文件名称" path="fileName" require-mark-placement="left" style="margin-right: 20px">
            <NInput v-model:value="formData.informationName" placeholder="请输入文件名称" />
          </NFormItem>
          <NFormItem label="上传类型" path="updataType" require-mark-placement="left" style="margin-right: 20px">
            <n-select v-model:value="formData.type" :options="updata" placeholder="请选择上传类型"
              @update:value="updataType" />
          </NFormItem>
          <NFormItem label="文件类型" path="fileType" require-mark-placement="left" style="margin-right: 20px">
            <n-select v-model:value="formData.fileType" :options="updata1" placeholder="请选择文件类型"
              @update:value="updataType1" />
          </NFormItem>
          <n-form-item label="模型上传">
            <n-upload action="http://192.168.2.53:8080/information/model/file" :headers="{
              'naive-info': 'hello!',
              }" :data="{
              'naive-data': 'cool! naive!',
              }" @before-upload="beforeUpload" @finish="finishUpload" @error="errorUpload" v-model:file-list="fileList"
              :show-file-list="false">
              <n-button @click="uploadIdentification = 'model'" color="#efefef">
                <img src="@/assets/fengmian.png" alt="" style="width: 15px; height: 14px; margin-right: 10px;">
                <div style="color: black;">文件上传</div>
              </n-button>
              <span style="color: #b6b6bb; margin-left: 20px; font-size: small;">上传无人机航测模型文件</span>
            </n-upload>
          </n-form-item>
          <n-form-item v-if="isShow01" label="上传状态">
            <div class="status">
              <n-space vertical>
                <n-spin :show="show01" :delay="1000">
                  <n-alert title="文件上传" :type='state01' style="width: 440px;">
                    {{ dataMessage }}
                  </n-alert>
                </n-spin>
              </n-space>
            </div>
          </n-form-item>
        </NForm>

        <template #footer>
          <NSpace justify="end">
            <NButton @click="createModal = false">取消</NButton>
            <NButton type="primary" @click="handleSubmit">确认</NButton>
          </NSpace>
        </template>
      </NCard>
    </NModal>

    <div>
      <NSpin :show="show">
        <NCard size="medium">
          <NSpace style="margin-bottom: 20px">
            <NButton color="#2198f2" style="padding: 0px 20px; border-radius: 5px" @click="handleAdd">
              <img src="@/assets/xinzeng.png" alt="" style="width: 10px; height: 10px; margin-right: 5px" />
              模型上传
            </NButton>
          </NSpace>

          <NDataTable :row-key="row => row.id" :columns="tableColumn" :data="tableData" :bordered="true"
            :pagination="false" tree-column-key="fileName" @update:checked-row-keys="handleCheck" />

          <div style="display: flex; justify-content: end; margin-top: 30px;">
            <ElPagination v-model:current-page="pageData.pageNum" v-model:page-size="pageData.pageSize"
              :page-sizes="[10, 20, 30, 40]" background="#2196f3" layout="sizes, prev, pager, next"
              :total="pageData.total" @size-change="handlePageSize" @current-change="handlePage" />
          </div>
        </NCard>
      </NSpin>
    </div>
  </div>
</template>

<style scoped>
:deep(.n-form-item-content > div) {
  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
}
:deep(.n-pagination .n-pagination-item.n-pagination-item--active) {
  background-color: #2196ed !important;
  color: white !important;
  border-color: #2196ed !important;
}
</style>
