<template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="tableType" @change="changeTable">
        <a-tab-pane :key="0" tab="四维看看" :disabled="loading" />
        <a-tab-pane :key="1" tab="四维看见" :disabled="loading" />
        <a-tab-pane :key="2" tab="深时点云场景" :disabled="loading" />
        <a-tab-pane :key="5" tab="深时Mesh场景" :disabled="loading" />
        <a-tab-pane :key="6" tab="深光点云场景" :disabled="loading" />
        <a-tab-pane :key="7" tab="深光Mesh场景" :disabled="loading" />
        <a-tab-pane :key="3" tab="四维双目Lite" :disabled="loading" />
      </a-tabs>
    </template>
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable" ref="tableRef">
        <template #toolbar>
          <!-- <a-button type="primary" @click="exportExcel"> 导出1</a-button> -->
        </template>
        <template #status="{ record }">
          <span v-if="record.status != '-1'">{{ record.statusString }}</span>
          <Tooltip v-else placement="right">
            <template #title>
              <span>失败原因:{{ record.buildErrorReason }}</span>
              <p>
                <span>serverPath：{{ record.dataSource }}</span>
              </p>
            </template>
            <span
              >{{ record.statusString }}
              <Icon icon="mdi:warning-octagon-outline" />
            </span>
          </Tooltip>
        </template>
        <template #href="{ record }">
          <a
            v-if="record.sceneName && record.thumb"
            target="_blank"
            :href="record.webSite || record.thumb"
            >{{ record.sceneName }}</a
          >
          <span v-else-if="record.sceneName">{{ record.sceneName }}</span>
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '迁移',
                disabled: !(record.status == 1 || record.status == -2),
                ifShow: getTypeCheckPerm('scenes-move') && tableType != 3,
                onClick: handleMove.bind(null, record),
              },
              {
                label: '解冻',
                disabled: !record.isColdStorage || !(record.status == 1 || record.status == -2),
                ifShow: getTypeCheckPerm('scenes-thaw'),
                onClick: handleColdStorage.bind(null, record),
              },
              {
                label: '下载',
                ifShow: getTypeCheckPerm('scenes-download') && tableType != 3,
                disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                //icon: 'carbon:download',
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '重算',
                disabled: record.status == 0 || (record.status == -2 && record.payStatus != 1),
                ifShow: getTypeCheckPerm('scenes-recalculate') && tableType != 3,
                popConfirm: {
                  title: '是否重算？',
                  confirm: handleReset.bind(null, record),
                },
              },
              {
                label: '复制',
                disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow: getTypeCheckPerm('scenes-copy') && tableType != 3,
                onClick: handleCopy.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                color: 'error',
                ifShow: getTypeCheckPerm('scenes-delete'),
                disabled: record.status == 0,
                //onClick: handleDelete.bind(null, record),
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <DownLoadModal
      :downloadOption="downloadOption"
      @cancel="afterClose"
      @register="registerDownModal"
      @update="reload"
      cancelText="取消下载"
      okText="下载"
      @cancelDownload="cancelDownload"
      :okButtonProps="{ disabled: canDownload }"
    />
    <MoveModal @update="reload" @register="registerMoveModal" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, reactive, toRefs, ref, unref } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableActionType,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import DownLoadModal from './modal/DownLoadModal.vue';
  import MoveModal from './modal/MoveModal.vue';
  import { Time } from '/@/components/Time';
  import { Icon } from '/@/components/Icon';
  import { Descriptions, Tabs, Progress, Tooltip } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    operateSceneList,
    sceneMove,
    sceneDelete,
    sceneReset,
    sceneRestStore,
    sceneDownload,
    checkDownLoad,
    downloadProcess,
    sceneCopy,
    rebuildScene,
  } from '/@/api/operate';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { func } from 'vue-types';
  import { truncate } from 'fs/promises';
  export default defineComponent({
    components: {
      DownLoadModal,
      MoveModal,
      BasicTable,
      TableAction,
      PageWrapper,
      Icon,
      Tooltip,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const loading = ref(false);
      const tableRef = ref<Nullable<TableActionType>>(null);
      const tableType = ref<Number>(0); //0看看 、1看见、2深时
      function columns(isobj): BasicColumn[] {
        return [
          {
            title: '场景标题',
            dataIndex: 'sceneName',
            slots: { customRender: 'href' },
            width: 150,
          },
          {
            title: '场景码',
            dataIndex: 'num',
            ellipsis: true,
            width: 180,
          },
          {
            title: '拍摄时间',
            dataIndex: 'createTime',
            sorter: true,
            width: 180,
            customRender: ({ record }) => {
              return (
                record.createTime &&
                h(Time, {
                  value: record.createTime,
                  mode: 'datetime',
                })
              );
            },
          },
          {
            title: 'obj生成状态',
            dataIndex: 'isObj',
            ellipsis: true,
            ifShow: isobj,
            width: 180,
            customRender: ({ record }) => {
              return record.isObj == 0 ? '未生成' : record.isObj == 1 ? '已生成' : '计算中';
            },
          },
          {
            title: '计算完成时间',
            dataIndex: 'amount',
            width: 180,
            customRender: ({ record }) => {
              return (
                (record.algorithmTime &&
                  h(Time, {
                    value: record.algorithmTime,
                    mode: 'datetime',
                  })) ||
                '-'
              );
            },
          },
          {
            title: 'SN码',
            dataIndex: 'snCode',
            width: 180,
          },
          {
            title: '点位数量',
            dataIndex: 'shootCount',
            width: 80,
          },
          {
            title: '场景大小',
            dataIndex: 'sceneSize',
            width: 80,
            customRender: ({ record }) => {
              return record.sceneSize && record.sceneSize != 0
                ? h('span', { class: 'sceneSize' }, Math.ceil(record.sceneSize / 1024 / 1024) + 'M')
                : '-';
            },
          },
          {
            title: '拍摄位置',
            dataIndex: 'addressComponent',
            width: 100,
            customRender: ({ record }) => {
              if (!record.addressComponent) {
                return '';
              }
              return record && record.addressComponent && record.addressComponent.city; // + district + township;
            },
          },
          {
            title: '是否复制',
            dataIndex: 'isCopy',
            width: 80,
            customRender: ({ record }) => {
              return record.isCopy ? '是' : '否';
            },
          },
          {
            title: '复制时间',
            dataIndex: 'copyTime',
            width: 180,
            customRender: ({ record }) => {
              return record.copyTime
                ? h(Time, {
                    value: record.copyTime,
                    mode: 'datetime',
                  })
                : '-';
            },
          },
          {
            title: '绑定账号',
            dataIndex: 'userName',
            width: 100,
          },
          {
            title: '浏览量',
            dataIndex: 'viewCount',
            sorter: true,
            width: 80,
          },
          {
            title: '状态',
            dataIndex: 'statusString',
            width: 120,
            slots: { customRender: 'status' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            slots: { customRender: 'action' },
            ifShow: true,
            fixed: 'right',
            flag: 'ACTION',
            width: 280,
          },
        ];
      }
      // const searchForm: Partial<FormProps> = {
      //   labelWidth: 100,
      //   schemas: [
      //     {
      //       field: 'sceneName',
      //       label: '场景标题',
      //       component: 'Input',
      //       componentProps: {
      //         maxLength: 100,
      //       },
      //       colProps: {
      //         xl: 7,
      //         xxl: 7,
      //       },
      //     },
      //     {
      //       field: 'snCode',
      //       label: 'SN码',
      //       component: 'Input',
      //       componentProps: {
      //         maxLength: 100,
      //       },
      //       colProps: {
      //         xl: 7,
      //         xxl: 7,
      //       },
      //     },
      //     {
      //       field: 'userName',
      //       label: '绑定账号',
      //       component: 'Input',
      //       componentProps: {
      //         maxLength: 100,
      //       },
      //       colProps: {
      //         xl: 6,
      //         xxl: 6,
      //       },
      //     },
      //   ],
      // };

      const searchFormSs: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        actionColOptions: {
          span: 24,
        },
        schemas: [
          {
            field: 'sceneName',
            label: '场景标题',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'num',
            label: '场景码',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'snCode',
            label: 'SN码',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'userName',
            label: '绑定账号',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'timeList',
            label: '拍摄时间段',
            component: 'RangePicker',
            componentProps: {
              maxLength: 100,
              minWidth: '385px',
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              showTime: true,
            },
            colProps: {
              xl: 8,
              xxl: 8,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerTable, { reload, setColumns }] = useTable({
        api: operateSceneList,
        title: `场景列表`,
        columns: columns(false),
        searchInfo: { type: tableType },
        useSearchForm: true,
        formConfig: searchFormSs,
        showTableSetting: true,
        beforeFetch: (T) => {
          loading.value = true;
          return T;
        },
        afterFetch: (T) => {
          loading.value = false;
          return T;
        },
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      function getTableAction() {
        const tableAction = unref(tableRef);
        if (!tableAction) {
          console.log('tableAction', tableAction, tableRef);
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

      function changeTable(val: string) {
        tableType.value = val;
        setColumns(columns(val == 2));
        // setColumns(columns)
        reload();
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '复制场景，场景归属在原相机下。<br/>确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num }).then(() => {
              message.success({
                content: '复制成功',
              });
              reload();
            });
          },
        });
      }
      async function handleDelete(record: Recordable) {
        console.log('handleDelete', record);
        // createConfirm({
        //   title: '删除',
        //   content: '确定要删除场景吗？',
        //   onOk: async () => {
        sceneDelete({ num: record.num }).then(() => {
          message.success({
            content: '删除成功',
          });

          reload();
        });
        //   },
        // });
      }
      async function handleColdStorage(record: Recordable) {
        createConfirm({
          title: '删除',
          content: '确定要解冻场景吗？',
          onOk: async () => {
            sceneRestStore({ num: record.num }).then(() => {
              message.success({
                content: '已提交解冻',
              });

              reload();
            });
          },
        });
      }
      async function handleMove(record: Recordable) {
        openMoveModal(true, {
          ...record,
        });
      }
      let timer: null = ref(null);
      const downloadOption = ref<Object>({});
      const canDownload = ref<boolean>(true);
      function handleDownload(record: Recordable) {
        console.log('handleDownload', record, tableType.value);
        let isObj = tableType.value == 5 ? 1 : 0;
        let params = { num: record.num, isObj: 0 };
        if (tableType.value == 4 || tableType.value == 5) {
          params.isObj = isObj;
        }
        canDownload.value = true;
        checkDownLoad(params).then((res) => {
          if (res.downloadStatus != 3) {
            // 未下载过，需要打包
            sceneDownload(params).then((res) => {
              console.log(res);
              openDownModal(true, {
                ...record,
                isObj: params.isObj,
              });
              if (res.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  downloadProcess(params).then((res) => {
                    if (res.status == '1003') {
                      createMessage.error('下载失败');
                      afterClose();
                      return;
                    }
                    if (res.percent >= 100) {
                      canDownload.value = false;
                      afterClose();
                    }
                    downloadOption.value = res;
                    console.log(res);
                  });
                }, 1000);
              }
            });
          } else {
            canDownload.value = false;
            window.open(res.downloadUrl);
          }
        });
      }
      function afterClose() {
        clearInterval(timer.value);
        timer.value = null;
      }
      function handleReset(record: Recordable) {
        console.log('handleReset', record);
        rebuildScene({ num: record.num }).then(() => {
          message.success({
            content: '操作成功',
          });
          reload();
        });
      }
      function getTypeCheckPerm(val) {
        let myType = tableType.value;
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`);
      }
      return {
        registerTable,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        handleColdStorage,
        tableType,
        loading,
        reload,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        getTypeCheckPerm,
      };
    },
  });
</script>
<style lang="less" scoped>
  // .tableHeader {
  //   height: 50px;
  //   display: flex;
  //   align-items: center;

  //   .item {
  //     font-size: 14px;
  //     color: #666;
  //     margin-right: 10px;
  //     cursor: pointer;
  //     &.active {
  //       font-weight: bold;
  //       color: #222;
  //     }
  //   }
  // }
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
