<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 { api_addRole, api_deleteRole, api_exportRoleData, api_getUserRole, api_menuPageGet, api_rolePage, api_updateRole } from '@/api';
import { roleRules } from '@/rules/rules';
import { deleteImageApi, getPageApi, postImageApi } from '@/api';
import { lyla } from '@lylajs/web'
import { render } from 'nprogress';

const message = useMessage();
const fileList = ref<[]>([])
// 常量和响应式数据
const tableData = ref([]);
const updata = [
  {
    label: '地形图',
    value: '1',
  },
  {
    label: '其他',
    value: '2'
  },
]
const updata1 = [
  {
    label: 'JPG',
    value: '1',
  },
  {
    label: 'PNG',
    value: '2',
  },
  {
    label: 'JPEG',
    value: '3',
  },
  {
    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('JPG文件上传中，请稍后')
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.type == 1) {
        text = '地形图'
      } else if (row.type == 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.fileType === 1) {
        text = 'JPG'
      } else if (row.fileType === 2) {
        text = 'PNG'
      } else if (row.fileType === 3) {
        text = 'JPEG'
      }
      return h('span', text)
    }
  },
  {
    title: '文件大小',
    key: 'fileSize',
    align: 'center',
    minWidth: 120
  },
  {
    title: '预览图',
    key: 'previewImage',
    align: 'center',
    minWidth: 120,
    render: (row: any) => {
      console.log(row);
      
      return h(NImage, {
        width: '50',
        lazy: true,
        height: '20',
        placeholder: "暂无",
        src: row.filePath
      });
    }
  },
  {
    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;
  isShow01.value = false;
  if (!formRef.value) return;
  formRef.value.validate(async errors => {
    if (!errors) {
      let res = await postImageApi(formData.value);
      if(res.data.code != 200) {
        message.error(res.data.msg)
      }
      search();
    } 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 deleteImageApi(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: ''
  };
  show01.value = false;
  createModal.value = true;
}

async function search() {
  let res = await getPageApi(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(data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) {
  console.log(data);
  const allowedTypes = ['image/png', 'image/jpg', 'image/jpeg'];
  if (!allowedTypes.includes(data.file.file?.type ?? '')) {
    message.error('仅支持 JPEG/JPG/PNG 三种图片格式上传');
    return false;
  }
  isShow01.value = true
  return 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) {
  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>
          <NFormItem label="文件上传">
            <n-upload action="http://192.168.2.53:8080/information/image/upload/iamge" :headers="{
                'naive-info': 'hello!'
              }" :data="{
                'naive-data': 'cool! naive!'
              }" @before-upload="beforeUpload" @finish="finishUpload" :show-file-list="false">
              <n-button color="#efefef" strong secondary>
                <img src="@/assets/fengmian.png" alt="" style="width: 15px; height: 14px; margin-right: 10px;">
                <div style="color: black;">文件上传</div>
              </n-button>
              <span style="color: #9f9f9f; margin-left: 30px;">上传JPG/JPEG/PNG文件</span>
            </n-upload>
          </NFormItem>
          <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>
