<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "TestDataset",
});
</script>

<script setup lang="ts">
import Icon from "@/components/Module/Icon/index.vue";
import ModuleCard from "@/views/dataManage/index/components/Card/ModuleCard.vue";
import { ref, h, unref, computed, reactive, onMounted } from "vue";
import { Button, Table, Popover, message, Modal, Space, Tooltip, Input } from "ant-design-vue";
import dayjs from "dayjs";
import { uuid } from "@/utils/util";

interface PropsType {
  state: Record<string, any>;
  api: Record<string, any>;
  requestMap: Record<string, any>;
  // data: Record<string, any>[];
  pageRef: HTMLElement;
}

const props = withDefaults(defineProps<PropsType>(), {
  state: () => {
    return {};
  },
  api: () => {
    return {};
  },
  requestMap: () => {
    return {};
  },
  pageRef: () => {
    return {};
  },
});

interface TableOptions {
  selectedRowKeys: string[];
  loading: boolean;
  list: Array<Record<string, any>>;
  total: number;
  pageParams: {
    page: number;
    size: number;
  };
}

// 表头
const columns = [
  {
    title: "数据集名称",
    dataIndex: "name",
    width: "300px",
  },
  {
    title: "批号",
    dataIndex: "track_ids",
    ellipsis: true,
    width: "300px",
  },
  {
    title: "数据集描述",
    dataIndex: "description",
    ellipsis: true,
  },
  {
    title: "导出时间",
    dataIndex: "timestamp",
    width: "300px",
  },
  {
    title: "操作",
    dataIndex: "operate",
    width: "100px",
  },
];

const downloadMethod = [
  {
    name: "导出为json",
    type: "json",
    key: "download_json",
  },
  {
    name: "导出为csv",
    type: "csv",
    key: "download_csv",
  },
  {
    name: "导出为mat",
    type: "mat",
    key: "download_mat",
  },
];

const loading = computed(() => {
  props.requestMap.trainDatasetListRequest.loading.value ||
    props.requestMap.deleteRequest.loading.value ||
    props.requestMap.updateRequest.loading.value;
});

// 表格配置项
const state = reactive<TableOptions>({
  loading: loading.value, // 是否在请求
  selectedRowKeys: [], // 选中的数据
  list: props.state.trainDataset, // 列表
  total: props.state.trainDataset.value.length, // 总数
  pageParams: {
    //分页
    page: 1,
    size: 10,
  },
});

const showList = computed(() => {
  const { page, size } = state.pageParams;
  const start = (page - 1) * size;
  const end = page * size;
  const listSlice = props.state.trainDataset.value.slice(start, end);

  return listSlice;
});

const getList = async () => {
  return await props.api.getTrainDataset();
};

// 开启编辑的索引
const editIndex = ref(-1);
const editField = ref("");
const editText = ref("");

const onUpdateEditText = (e: Record<string, any>) => {
  editText.value = e.target.value;
};

// 设置编辑的索引
const onSetEditIndex = (number: number, field?: string) => {
  editField.value = field || "";
  editIndex.value = number;
  if (number == -1) {
    editText.value = "";
  } else {
    const useData = state.list[number];
    const useText = useData[field as string];
    editText.value = useText;
  }
};

// 更新数据
const onUpdate = async (info: Record<string, any>) => {
  const params = {
    id: info.id,
    name: info.name,
    description: info.description,
  };
  console.log("info", info, params);
  const res = await props.api.updateDataset(params);
  if (res?.code == 200) {
    message.success("修改成功");
  }
  await getList();
};

// 完成编辑
const afterEdit = async (info: Record<string, any>) => {
  await onUpdate(info);
  onSetEditIndex(-1);
};

const onDelete = async (info: Record<string, any>) => {
  const res = await props.api.deleteDataset(info.id);
  return res;
};

const createDeleteProps = (info: Record<string, any>) => {
  return {
    centered: true,
    title: h("div", { style: "font-size: 16px" }, "删除数据"),
    icon: h("span"),
    content: h(
      "div",
      { style: "font-size: 16px; margin-bottom: 20px" },
      "确定要删除当前数据吗?本次操作无法撤回",
    ),
    okText: "确定",
    cancelText: "取消",
    onOk: async () => {
      const res = await onDelete(info);
      if (res?.code == 200) {
        await getList();
      }
      return res;
    },
    onCancel() {},
  };
};

// 删除
const onShowDelete = (info: Record<string, any>) => {
  const modalProps = createDeleteProps(info);
  Modal.confirm(modalProps);
};

// 下载
const onDownload = (info: Record<string, any>) => {
  const { name, id, type } = info;
  props.api.onDatasetDownload({
    id: id,
    type: type,
    fileName: name + `训练集.${type}`,
  });
};

// 操作列表
const operateList: any[] = [];

// 操作区点击
const onMenuSelect = (item: Record<string, any>) => {
  console.log("item", item);
  const eventMap: Record<string, (...args: any[]) => any> = {};
  if (eventMap[item.key]) {
    eventMap[item.key]();
  }
};

const tableContainRef = ref();

onMounted(() => {});

const prefix = "dataset-test";
</script>

<template>
  <div :class="prefix">
    <ModuleCard title="训练集">
      <template #head-extra>
        <a-space :size="20">
          <Button
            type="primary"
            v-for="item in operateList"
            :class="item.customClass"
            @click="onMenuSelect(item)"
          >
            <template #icon>
              <Icon :name="item.icon" />
            </template>
            {{ item.name }}
          </Button>
        </a-space>
      </template>
      <div>
        <Table
          :class="`${prefix}-table`"
          :loading="loading"
          rowKey="id"
          :dataSource="showList"
          :columns="columns"
          :pagination="{
            showSizeChanger: false,
            pageSize: state.pageParams.size,
            current: state.pageParams.page,
            total: props.state.testDataset.value.length,
          }"
        >
          <template #bodyCell="{ column, text, index, record }">
            <template v-if="column.dataIndex == 'track_ids'">
              <Popover arrow-point-at-center :getPopupContainer="(e: HTMLElement) => props.pageRef">
                <template #content>
                  <div class="wrapper">
                    <div class="index-box" v-for="(item, index) in text.split(',')">
                      <div class="index-box-circle">{{ index + 1 }}</div>
                      <div class="index-box-text">{{ item }}</div>
                    </div>
                  </div>
                </template>
                <div class="marker-text">
                  {{ text }}
                </div>
              </Popover>
            </template>
            <template v-if="column.dataIndex == 'timestamp'">
              {{ dayjs(text).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
            <!-- 数据名称 -->
            <template v-if="['name', 'description'].includes(column.dataIndex as string)">
              <div class="marker-row" v-if="editIndex == index && editField == column.dataIndex">
                <div class="marker-input">
                  <Input :value="editText" @change="onUpdateEditText" />
                </div>
                <div class="marker-operate">
                  <Space>
                    <Button
                      type="text"
                      @click="
                        afterEdit({
                          ...record,
                          [column.dataIndex]: editText,
                        })
                      "
                    >
                      <template #icon>
                        <Icon name="correct" style="font-size: 20px" />
                      </template>
                    </Button>
                    <Button type="text" @click="onSetEditIndex(-1)">
                      <template #icon>
                        <Icon name="close" />
                      </template>
                    </Button>
                  </Space>
                </div>
              </div>
              <div class="marker-row" v-else @click="onSetEditIndex(index, column.dataIndex)">
                <div class="marker-text">{{ text }}</div>
              </div>
            </template>
            <!-- 删除 -->
            <template v-if="column.dataIndex === 'operate'">
              <Space :size="10">
                <Popover
                  arrow-point-at-center
                  :getPopupContainer="(e: HTMLElement) => props.pageRef"
                >
                  <template #content>
                    <div
                      v-for="opt in downloadMethod"
                      class="download-option"
                      @click="
                        onDownload({
                          ...record,
                          type: opt.type,
                        })
                      "
                    >
                      {{ opt.name }}
                    </div>
                  </template>
                  <Button type="text" class="primary-btn">
                    <template #icon>
                      <Icon name="save" />
                    </template>
                  </Button>
                </Popover>

                <Tooltip title="删除" class="delete-btn">
                  <Button type="text" @click="onShowDelete(record)">
                    <template #icon>
                      <Icon name="delete" />
                    </template>
                  </Button>
                </Tooltip>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </ModuleCard>
  </div>
</template>

<style lang="scss" scoped>
$prefix: "dataset-test";

.#{$prefix} {
  width: 100%;
  height: 100%;
  .custom-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    border-radius: 4px 4px 4px 4px;
    padding: 8px 16px;
  }
  .grey-btn {
    background: #aab5c4;
  }
  .edit-btn {
    color: #3662e3;
  }
  .primary-btn {
    color: #1677ff;
  }
  .delete-btn {
    color: #dd524c;
  }
  .marker-row {
    width: 100%;
    max-width: 500px;
    display: flex;
    align-items: center;
    justify-self: start;
    gap: 10px;
    &:hover {
      .marker-edit {
        display: block;
      }
    }
  }
  .marker-input {
    flex: 1;
  }
  .marker-operate {
    margin-left: auto;
  }
  .marker-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .marker-edit {
    margin-left: auto;
    display: none;
  }

  :deep(.ant-table-wrapper) {
    .ant-table {
      border-radius: 0;
      background: transparent;
      .ant-table-thead {
        > tr > th {
          border-bottom: none;
          background-color: #fff;
          &::before {
            background-color: #d8d8d8 !important;
          }
        }
        > tr > td {
          border-top: none;
        }
      }
      .ant-table-tbody > tr.ant-table-placeholder:hover > td {
        background-color: transparent;
      }
    }

    .ant-table-container table > thead > tr:first-child > *:first-child {
      border-start-start-radius: 0;
    }
    .ant-table-container table > thead > tr:first-child > *:last-child {
      border-start-end-radius: 0px;
    }
  }
}
</style>
