<template>
  <div>
    <div class="upload">
      <a-upload
        v-model:file-list="fileList"
        list-type="picture-card"
        multiple
        :showUploadList="false"
        :custom-request="customRequest"
      >
        <div>
          <PlusOutlined />
          <div style="margin-top: 8px">上传图片</div>
        </div>
      </a-upload>
    </div>
    <div class="table">
      状态筛选：
      <a-select
        v-model:value="selectStatus"
        mode="multiple"
        style="width: 90%; margin-top: 5px; margin-bottom: 5px"
        allowClear
        :options="[
          {
            value: 'uploading',
            label: '上传中',
          },
          {
            value: 'done',
            label: '上传成功',
          },
          {
            value: 'error',
            label: '上传失败',
          },
          {
            value: 'updateSuccess',
            label: '插入成功',
          },
          {
            value: 'updateError',
            label: '插入失败',
          },
        ]"
      />
      <a-table
        :columns="uploadColumns"
        :data-source="filterData"
        :pagination="false"
        bordered
        :scroll="{ y: 600 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'size'">
            {{ parseFloat(record.size / 1024 / 1024).toFixed(2) }} MB
          </template>
          <template v-if="column.dataIndex === 'percent'">
            <a-progress
              v-if="record.status == 'error'"
              :percent="record.percent"
              status="exception"
            />
            <a-progress
              v-if="['done', 'updateSuccess', 'updateError'].includes(record.status)"
              :percent="record.percent"
            />
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag color="processing" v-if="record.status == 'uploading'">上传中</a-tag>
            <a-tag color="success" v-if="record.status == 'done'">上传成功</a-tag>
            <a-tag color="error" v-if="record.status == 'error'">上传失败</a-tag>
            <a-tag color="green" v-if="record.status == 'updateSuccess'">插入成功</a-tag>
            <a-tag color="red" v-if="record.status == 'updateError'">审核失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'url' || column.dataIndex === 'message'">
            {{ record.url || record.message }}
          </template>
        </template>
      </a-table>
      <div class="updateDiv">
        <a-tooltip
          v-if="
            fileList && fileList.length > 0 && fileList.find((item) => item.status == 'updateError')
          "
        >
          <template #title>在报【有未审核的图片，不允许上传】的错误时，可以点击</template>
          <a-button type="primary" @click="funCheckCxjgPic" style="margin-right: 10px">
            审核图片
          </a-button>
        </a-tooltip>
        <!-- {{ .length }} -->
        <a-button type="primary" @click="startUploadCXJGData">
          将上传成功的图片插入到数据库
        </a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { defineProps, ref, watch, onMounted, defineEmits, computed } from 'vue';
  import { PlusOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';
  import { UpdateCxjgData, CheckCxjgPic } from '@/api/demo/system';
  import { uploadColumns } from './keepSupervision.data';
  import { message } from 'ant-design-vue';

  const { VITE_GLOB_INFO_IMAGE_URL } = getAppEnvConfig();

  // 上传列表
  const fileList: any = ref();
  const selectStatus = ref([]);
  const filterData = computed(() => {
    if (fileList.value && selectStatus.value.length > 0) {
      return fileList.value.filter((item) => selectStatus.value.includes(item.status));
    } else {
      return fileList.value;
    }
  });

  // 上传
  const customRequest = (file) => {
    const formData = new FormData();
    formData.append('files', file.file);
    axios({
      method: 'post',
      url: `${VITE_GLOB_INFO_IMAGE_URL}/api/Platform/Upload`,
      params: { project: 'DroneEnforcement' },
      data: formData,
      headers: {
        'Content-type': 'multipart/form-data',
      },
    }).then((res) => {
      const index = fileList.value.findIndex((item) => item.uid === file.file.uid);
      // 上传成功
      if (res.data.code == '200') {
        let data = res.data.result;
        fileList.value[index] = {
          ...fileList.value[index],
          percent: 100,
          status: 'done',
          url: data[0].filePath,
        };
      } else {
        // 上传失败
        fileList.value[index] = {
          ...fileList.value[index],
          percent: 0,
          status: 'error',
          url: '',
          message: res.data.message,
        };
      }
    });
  };

  // 持续监管-图片插入启动
  async function startUploadCXJGData() {
    const list = fileList.value;
    if (!list || list.length === 0) return;
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.status === 'done' || item.status === 'updateError') {
        // 等待上传完成并返回 true 后，再继续下一个循环
        await UpdateUploadCXJGData(item);
      }
    }
  }

  // 持续监管-图片插入
  async function UpdateUploadCXJGData(value) {
    let caseid = value.name.split('.').slice(0, -1).join('.');
    if (caseid.includes('_')) {
      caseid = caseid.split('_').slice(0, 1).join('_');
    }
    const index = fileList.value.findIndex((item) => item.uid === value.uid);
    if (index === -1) return false; // 如果找不到对应文件项，直接返回
    let querys = {
      caseid: caseid,
      path: value.url,
    };
    try {
      const res1 = await UpdateCxjgData(querys);
      if (res1) {
        // 图片上传成功，开始审核
        const res2 = await CheckCxjgPic({ id: caseid });
        if (res2) {
          // 审核通过
          fileList.value[index] = {
            ...fileList.value[index],
            status: 'updateSuccess',
          };
        } else {
          // 审核失败
          fileList.value[index] = {
            ...fileList.value[index],
            status: 'updateError',
          };
        }
      } else {
        // 上传失败
        fileList.value[index] = {
          ...fileList.value[index],
          status: 'updateError',
        };
        message.error('有未审核的图片，不允许上传');
      }
    } catch (error) {
      console.error('上传或审核出错:', error);
      fileList.value[index] = {
        ...fileList.value[index],
        status: 'updateError',
      };
    }
  }

  // 持续监管-图片审核
  async function funCheckCxjgPic() {
    const list = fileList.value;
    if (!list || list.length === 0) return;
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.status === 'updateError') {
        // 等待上传完成并返回 true 后，再继续下一个循环
        let caseid = item.name.split('.').slice(0, -1).join('.');
        if (caseid.includes('_')) {
          caseid = caseid.split('_').slice(0, 1).join('_');
        }
        await CheckCxjgPic({ id: caseid });
        const index = fileList.value.findIndex((item) => item.uid === item.uid);
        fileList.value[index] = {
          ...fileList.value[index],
          status: 'updateSuccess',
        };
      }
    }
  }
</script>
<style lang="less" scoped>
  .upload {
    width: 100%;
    margin-left: 20px;
  }
  .table {
    // width: 95%;
    margin-left: 20px;
    margin-right: 20px;
  }
  .updateDiv {
    position: absolute;
    bottom: 10px;
    right: 10px;
    gap: 10px;
  }

  ::v-deep .ant-select-selection-item {
    width: 85px !important;
  }
</style>
