<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <LeftTree ref="childRef" class="w-1/5 xl:w-1/6" @select="handleSelect" />
    <BasicTable class="w-4/5 xl:w-5/6" @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <!-- <PermissionBtn @btnEvent="onBtnClicked"></PermissionBtn> -->
        <a-button :icon="h(PlusOutlined)" type="primary" @click="addFolder">新建文件夹</a-button>
        <a-button :icon="h(ColumnHeightOutlined)" @click="moveFolderOrFile">移动</a-button>
        <a-button :icon="h(DeleteOutlined)" @click="deleteFolderOrFile">删除 </a-button>
        <a-button :icon="h(DownloadOutlined)" @click="compressFolderOrFile">压缩</a-button>
        <a-radio-group v-model:value="tableType">
          <a-radio-button value="table"><BarsOutlined /></a-radio-button>
          <a-radio-button value="store"><AppstoreOutlined /></a-radio-button>
        </a-radio-group>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <FolderOpenOutlined v-if="record.type == 'folder'" style="font-size: 20px" />
          <img v-if="record.type == 'img'" :src="record.url" :width="30" :height="20" />
          {{ record.name }}
        </template>
        <template v-if="column.key === 'size'">
          {{ record.size ? record.size : '-' }}
        </template>
        <template v-if="column.key === 'label'">
          <div v-if="record.label && record.label.length > 0">
            <a-tag color="success" v-for="la in record.label" :key="la">{{ la }}</a-tag>
          </div>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="text">
            <EditOutlined @click="renameRecord(record)" />
          </a-button>
          <a-button type="text" v-if="record.type != 'folder'">
            <EyeOutlined @click="lookRecord(record)" />
          </a-button>
        </template>
      </template>
    </BasicTable>
    <!-- 新建文件夹 -->
    <AddFolderModal @register="addFolderModal" @success="handleSuccess" />
    <!-- 移动 -->
    <MoveFileModal @register="moveFileModal" @success="handleSuccess" />
    <!-- 压缩 -->
    <CompressFileModal @register="compressFileModal" @success="handleSuccess" />
    <!-- 重命名 -->
    <RenameModal @register="renameModal" @success="handleSuccess" />
    <!-- 预览弹窗 -->
    <a-modal
      v-model:open="open"
      width="100%"
      wrap-class-name="full-modal"
      :centered="true"
      :closable="false"
      :footer="null"
      :destroyOnClose="true"
      :mask="false"
      :maskClosable="false"
      @ok="handleOk"
    >
      <Preview
        v-if="nowPreviewRecord.type == 'img' || nowPreviewRecord.type == 'video'"
        :nowPreviewRecord="nowPreviewRecord"
        :previewRecordList="previewRecordList"
        @chooseNowPreviewRecord="chooseNowPreviewRecord"
        @closeModal="closeModal"
        @reloadTable="reload"
      />
      <ModelModal
        v-if="nowPreviewRecord.type.includes('model')"
        :nowPreviewRecord="nowPreviewRecord"
        :previewRecordList="previewRecordList"
        @chooseNowPreviewRecord="chooseNowPreviewRecord"
        @closeModal="closeModal"
        @reloadTable="reload"
      />
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, ref, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getOrgList, deleteDept } from '@/api/demo/system';
  import { PageWrapper } from '@/components/Page';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import {
    EditOutlined,
    DeleteOutlined,
    PlusOutlined,
    ColumnHeightOutlined,
    DownloadOutlined,
    AppstoreOutlined,
    BarsOutlined,
    FolderOutlined,
    FolderOpenOutlined,
    EyeOutlined,
  } from '@ant-design/icons-vue';
  import LeftTree from './LeftTree.vue';
  import { AddFolderModal } from './modal/modal';
  import { MoveFileModal } from './modal/modal';
  import { CompressFileModal } from './modal/modal';
  import { RenameModal } from './modal/modal';
  import Preview from './preview/preview.vue';
  import ModelModal from './priview2D3D/modelModal.vue';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema } from './modal.data';
  import dayjs from 'dayjs';

  const { createConfirm, createMessage } = useMessage();
  const data = ref([
    {
      id: '1',
      name: '普通飞行1',
      createtime: '2025-03-24 18:13:17',
      type: 'folder',
      children: [
        {
          id: '21',
          name: '普通飞行2-1',
          createtime: '2025-03-24 18:13:17',
          type: 'folder',
          children: [
            {
              id: '31',
              name: '普通飞行3-1',
              createtime: '2025-03-24 18:13:17',
              type: 'img',
            },
          ],
        },
        {
          id: '22',
          name: '普通飞行2-2',
          createtime: '2025-03-24 18:13:17',
          type: 'folder',
          children: [
            {
              id: '32',
              name: '普通飞行3-2',
              createtime: '2025-03-24 18:13:17',
              type: 'img',
            },
            {
              id: '33',
              name: '普通飞行3-3',
              createtime: '2025-03-24 18:13:17',
              type: 'img',
            },
          ],
        },
      ],
    },
    {
      id: '2',
      name: '图片',
      createtime: '2025-03-24 18:13:17',
      type: 'folder',
      children: [
        {
          id: '1-2',
          name: '南山风景照.jpg',
          createTime: '2020-10-22 17:33:22',
          type: 'img',
          url: 'https://cdn.colorhub.me/QgpUMkZxNhU/rs:auto:0:500:0/g:ce/fn:colorhub/bG9jYWw6Ly8vZmIvNmYvMjlkMTE1NjRkNmI5ZmRhOTczYmU3ZmUyNmMyMDkwM2MwZjU5ZmI2Zi5qcGVn.webp',
          imgtype: '原片',
          taskname: '佛山大火救援项目',
          airlineName: '火灾救援勘查航线',
          width: 889,
          height: 500,
          size: '6.2M',
          photographFeiji: '救援机1007',
          photographNumber: 'GD610',
          photographMan: 'zachzhou',
          photographTime: '2020-10-22 00:00:00',
          label: ['人', '车'],
          lat: 35.362625,
          lng: 118.033886,
          canvasJson:
            '{"version":"4.6.0","objects":[{"type":"path","version":"4.6.0","originX":"left","originY":"top","left":520.5,"top":634,"width":0,"height":0,"fill":null,"stroke":"#ffffff","strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"round","strokeDashOffset":0,"strokeLineJoin":"round","strokeUniform":false,"strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"path":[["M",520.999,634.5],["L",521.001,634.5]]},{"type":"rect","version":"4.6.0","originX":"left","originY":"top","left":523,"top":352.5,"width":100,"height":100,"fill":"#ffffff00","stroke":"#ffffff","strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.73,"scaleY":0.73,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"rx":0,"ry":0},{"type":"textbox","version":"4.6.0","originX":"left","originY":"top","left":523,"top":426.5,"width":200,"height":22.6,"fill":"#ffffff","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"fontFamily":"Times New Roman","fontWeight":"normal","fontSize":20,"text":"太阳","underline":false,"overline":false,"linethrough":false,"textAlign":"left","fontStyle":"normal","lineHeight":1.16,"textBackgroundColor":"","charSpacing":0,"styles":{},"direction":"ltr","path":null,"pathStartOffset":0,"pathSide":"left","minWidth":20,"splitByGrapheme":false},{"type":"path","version":"4.6.0","originX":"left","originY":"top","left":784,"top":436.5,"width":190.01,"height":85.01,"fill":null,"stroke":"#ffffff","strokeWidth":4,"strokeDashArray":null,"strokeLineCap":"round","strokeDashOffset":0,"strokeLineJoin":"round","strokeUniform":false,"strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"path":[["M",785.996,438.496],["Q",786,438.5,786.5,438.5],["Q",787,438.5,790.5,440],["Q",794,441.5,798.5,443.5],["Q",803,445.5,808,448],["Q",813,450.5,820,453.5],["Q",827,456.5,880,480.5],["Q",933,504.5,940,508],["Q",947,511.5,952.5,514],["Q",958,516.5,962.5,518],["Q",967,519.5,970,521],["Q",973,522.5,974.5,523],["L",976.004,523.504]]},{"type":"path","version":"4.6.0","originX":"left","originY":"top","left":808,"top":417.5,"width":123.01,"height":124.01,"fill":null,"stroke":"#ffffff","strokeWidth":4,"strokeDashArray":null,"strokeLineCap":"round","strokeDashOffset":0,"strokeLineJoin":"round","strokeUniform":false,"strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"path":[["M",933.004,419.496],["Q",933,419.5,931.5,420.5],["Q",930,421.5,928,425],["Q",926,428.5,921.5,433],["Q",917,437.5,914,441.5],["Q",911,445.5,905.5,450.5],["Q",900,455.5,894,462],["Q",888,468.5,883,473.5],["Q",878,478.5,872,484.5],["Q",866,490.5,861.5,495],["Q",857,499.5,851,504.5],["Q",845,509.5,841.5,513],["Q",838,516.5,833.5,520],["Q",829,523.5,826,526.5],["Q",823,529.5,820,533],["Q",817,536.5,815,538],["Q",813,539.5,812.5,540.5],["Q",812,541.5,811,542.5],["L",809.996,543.504]]}],"backgroundImage":{"type":"image","version":"4.6.0","originX":"left","originY":"top","left":0,"top":0,"width":889,"height":500,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1.46,"scaleY":1.6,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://cdn.colorhub.me/QgpUMkZxNhU/rs:auto:0:500:0/g:ce/fn:colorhub/bG9jYWw6Ly8vZmIvNmYvMjlkMTE1NjRkNmI5ZmRhOTczYmU3ZmUyNmMyMDkwM2MwZjU5ZmI2Zi5qcGVn.webp","crossOrigin":null,"filters":[]}}',
        },
        {
          id: '1-3',
          name: '风景图.jpg',
          createTime: '2020-10-22 17:33:22',
          type: 'img',
          url: 'https://m.tuniucdn.com/fb2/t1/G5/M00/44/52/Cii-s1soezyIF2UxABn76u-yKl8AAIwBgB34jAAGfwC3020871',
          imgtype: '原片2',
          taskname: '佛山大火救援项目2',
          airlineName: '火灾救援勘查航线2',
          width: 2000,
          height: 1334,
          size: '1.63M',
          photographFeiji: '救援机1008',
          photographNumber: 'GD610',
          photographMan: 'zachzhou',
          photographTime: '2020-10-22 00:00:00',
          label: ['人', '车'],
          lat: 35.362625,
          lng: 118.033886,
          canvasJson:
            '{"version":"4.6.0","objects":[],"backgroundImage":{"type":"image","version":"4.6.0","originX":"left","originY":"top","left":0,"top":0,"width":2000,"height":1334,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.65,"scaleY":0.6,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://m.tuniucdn.com/fb2/t1/G5/M00/44/52/Cii-s1soezyIF2UxABn76u-yKl8AAIwBgB34jAAGfwC3020871","crossOrigin":null,"filters":[]}}',
        },
        {
          id: '1-4',
          name: '红外照片.jpg',
          createTime: '2020-10-22 17:33:22',
          type: 'img',
          url: 'https://pic.rmb.bdstatic.com/bjh/gallery/8c885a0e3cf0647b60548535e2e9ca39.jpeg',
          imgtype: '红外照片',
          taskname: '佛山大火救援项目-红外照片',
          airlineName: '火灾救援勘查航线',
          width: 640,
          height: 480,
          size: '6.2M',
          photographFeiji: '救援机1007',
          photographNumber: 'GD610',
          photographMan: 'zachzhou',
          photographTime: '2020-10-22 00:00:00',
          label: ['人', '车'],
          lat: 35.362625,
          lng: 118.033886,
        },
        {
          id: '1-5',
          name: '广角照片.jpg',
          createTime: '2020-10-22 17:33:22',
          type: 'img',
          url: 'https://img2.baidu.com/it/u=2490853491,3226002419&fm=253&fmt=auto&app=138&f=JPEG?w=749&h=500',
          imgtype: '广角照片',
          taskname: '佛山大火救援项目-广角照片',
          airlineName: '火灾救援勘查航线',
          width: 749,
          height: 500,
          size: '6.2M',
          photographFeiji: '救援机1007',
          photographNumber: 'GD610',
          photographMan: 'zachzhou',
          photographTime: '2020-10-22 00:00:00',
          label: ['人', '车'],
          lat: 35.362625,
          lng: 118.033886,
        },
        {
          id: '1-6',
          name: '变焦照片.jpg',
          createTime: '2020-10-22 17:33:22',
          type: 'img',
          url: 'https://img2.baidu.com/it/u=3778652155,475195343&fm=253&fmt=auto&app=138&f=PNG?w=500&h=518',
          imgtype: '变焦照片',
          taskname: '佛山大火救援项目-变焦照片',
          airlineName: '火灾救援勘查航线',
          width: 500,
          height: 518,
          size: '6.2M',
          photographFeiji: '救援机1007',
          photographNumber: 'GD610',
          photographMan: 'zachzhou',
          photographTime: '2020-10-22 00:00:00',
          label: ['人', '车'],
          lat: 35.362625,
          lng: 118.033886,
        },
      ],
    },
    {
      id: '3',
      name: '视频',
      createtime: '2025-03-24 18:13:17',
      type: 'folder',
      children: [
        {
          id: '3-4',
          name: 'XZD153狼窝沟西南',
          createTime: '',
          type: 'video',
          url: '74b95e6575d741489b9a9061bb646467',
          manufacturer: '海康',
        },
        {
          id: '3-5',
          name: '费县马庄镇陈家鱼后村南斜坡后村',
          createTime: '',
          type: 'video',
          url: 'http://111.36.45.20:18000/flv/hls/H-dcb1ea7388588111.flv',
          manufacturer: '腾讯',
        },
        {
          id: '3-6',
          name: '可落',
          createTime: '',
          type: 'video',
          url: '8H03AA1PAG8D9BF',
          manufacturer: '乐橙',
        },
        {
          id: '3-7',
          name: '费县薛庄镇东张林村村南可见光',
          createTime: '',
          type: 'video',
          url: '37130100181328000392',
          manufacturer: '青犀',
        },
      ],
    },
    {
      id: '4',
      name: '模型',
      createtime: '2025-03-24 18:13:17',
      type: 'folder',
      children: [
        {
          id: '4-1',
          name: '天空之城 二维模型',
          createtime: '2025-03-24 18:13:17',
          type: 'model2D',
          url: 'https://m.tuniucdn.com/fb2/t1/G5/M00/44/52/Cii-s1soezyIF2UxABn76u-yKl8AAIwBgB34jAAGfwC3020871',
          boundary: {
            end_lat: 22.57965964566081,
            end_lng: 113.93899440765381,
            max_level: 23,
            min_level: 12,
            start_lat: 22.578193485606185,
            start_lng: 113.93697738647461,
          },
        },
        {
          id: '4-2',
          name: '天空之城 三维模型',
          createtime: '2025-03-24 18:13:17',
          type: 'model3D',
          url: 'https://m.tuniucdn.com/fb2/t1/G5/M00/44/52/Cii-s1soezyIF2UxABn76u-yKl8AAIwBgB34jAAGfwC3020871',
          boundary: {
            end_lat: 22.57965964566081,
            end_lng: 113.93899440765381,
            max_level: 23,
            min_level: 12,
            start_lat: 22.578193485606185,
            start_lng: 113.93697738647461,
          },
        },
      ],
    },
  ]);

  const tableType = ref('table');
  const searchInfo = reactive<Recordable>({});
  const searchParams = ref();
  const [registerTable, { reload, getSelectRows, getDataSource, clearSelectedRowKeys }] = useTable({
    // api: getOrgList,
    dataSource: data,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'checkbox',
    },
    striped: false,
    bordered: false,
    inset: false,
    tableSetting: {
      redo: false,
      size: false,
      setting: false,
    },
    useSearchForm: true,
    showIndexColumn: false,
    showTableSetting: true,
    handleSearchInfoFn(info) {
      console.log(info);
      console.log(searchInfo.value);

      searchParams.value = info;
      return info;
    },
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      var temp = {
        startTime: dayjs(data.startTime).startOf('month').format('YYYY-MM-DD'),
        endTime: dayjs(data.endTime).endOf('month').format('YYYY-MM-DD HH:mm:ss'),
      };
      return temp;
    },
    afterFetch: (res) => {
      console.log(res);
    },
  });

  function handleSelect(orgId = '') {
    searchInfo.orgId = orgId;
    reload();
  }

  const childRef = ref<any>();
  function handleSuccess() {
    clearSelectedRowKeys();
    childRef.value.fetch();
    reload();
  }

  // 弹窗----------------------------------------------------------------------
  // 新建文件夹
  const [addFolderModal, { openModal: openAddFolderModal }] = useModal();
  // 移动
  const [moveFileModal, { openModal: openMoveFileModal }] = useModal();
  // 压缩
  const [compressFileModal, { openModal: openCompressFileModal }] = useModal();
  // 重命名
  const [renameModal, { openModal: openRenameModal }] = useModal();

  // 新建文件夹
  function addFolder() {
    let rows = getSelectRows();
    let record: any = null;
    if (rows.length == 1) {
      if (rows[0].type == 'folder') {
        record = rows[0];
      } else {
        record = findParentIdById(getDataSource(), rows[0].id);
      }
    }
    openAddFolderModal(true, {
      record,
    });
  }

  // 获取父元素
  function findParentIdById(tree, targetId) {
    function recurse(nodes) {
      for (let node of nodes) {
        if (node.children) {
          for (let child of node.children) {
            if (child.id === targetId) {
              return node;
            }
            const found = recurse([child]);
            if (found) return found;
          }
        }
      }
      return null;
    }
    return recurse(tree);
  }

  // 移动文件
  function moveFolderOrFile() {
    let rows = getSelectRows();
    if (rows.length > 0) {
      const record = rows;
      openMoveFileModal(true, {
        tableData: getDataSource(),
        record,
      });
    } else {
      return createMessage.warn('请选择一个或者多个文件/文件夹进行移动');
    }
  }

  // 删除
  async function deleteFolderOrFile() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个或者多个文件/文件夹进行删除');
    }
    const query = rows.map((item) => item.id);
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前部门吗',
      onOk: async () => {
        // const data = await deleteDept(query);
        const data = null;
        if (data) {
          handleSuccess();
          createMessage.success('删除成功');
        } else {
          createMessage.error('删除失败');
        }
      },
    });
  }

  // 压缩
  function compressFolderOrFile() {
    let rows = getSelectRows();
    if (rows.length > 0) {
      const record = rows;
      openCompressFileModal(true, {
        tableData: getDataSource(),
        record,
      });
    } else {
      return createMessage.warn('请选择一个或者多个文件/文件夹压缩');
    }
  }

  // 重命名
  function renameRecord(record) {
    openRenameModal(true, {
      record,
    });
  }

  // 预览----------------------------------------------------------------------
  const open = ref(false);
  // 预览
  const nowPreviewRecord: any = ref();
  const previewRecordList: any = ref([]);
  function lookRecord(record) {
    open.value = true;
    nowPreviewRecord.value = record;
    previewRecordList.value = findParentIdById(getDataSource(), record.id)?.children;
    if (!previewRecordList.value) {
      previewRecordList.value = getDataSource();
    }
  }

  // 图片选择
  function chooseNowPreviewRecord(value) {
    nowPreviewRecord.value = value;
  }
  // 关闭
  function closeModal() {
    open.value = false;
  }
</script>
