<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "DataImport",
});
</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, unref, computed, reactive, onMounted, h } from "vue";
import { Space, Button, Table, message, Tooltip, Modal, Tag } from "ant-design-vue";
// import { EyeOutlined } from ''
import { useMain } from "@/views/dataManage/index/hooks/mock.ts";
import dayjs from "dayjs";
import { router } from "@/router/index.ts";
import TaskFormModal from "@/views/modelTraining/index/components/Modal/TaskFormModal.vue";
// import ExportModal from "@/views/dataManage/index/components/Modal/ExportModal.vue";

// const { generatorList, sleep } = useMain();

interface PropsType {
  task: Record<string, any>;
  options: Record<string, any>;
  // state: Record<string, any>;
  // api: Record<string, any>;
  // requestMap: Record<string, any>;
}

const props = withDefaults(defineProps<PropsType>(), {
  task: () => {
    return {};
  },
  options: () => {
    return {};
  },
});

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

const { generatorList } = useMain();

const statusMap: Record<string, any> = {
  running: "训练中",
  finished: "训练完成",
  failed: "训练失败",
  stopped: "训练中止",
};

const statusColorMap: Record<string, any> = {
  running: "blue",
  finished: "green",
  failed: "red",
  stopped: "orange",
};

// 表头
const columns = [
  {
    title: "任务id",
    dataIndex: "id",
  },
  {
    title: "模型名称",
    dataIndex: "model_name",
    width: "200px",
  },
  {
    title: "任务描述",
    dataIndex: "task_description",
    width: "400px",
  },
  {
    title: "数据集",
    dataIndex: "dataset_name",
  },
  {
    title: "训练状态",
    dataIndex: "status",
  },
  // {
  //   title: "导入时间",
  //   dataIndex: "createTime",
  // },
  {
    title: "操作",
    dataIndex: "operate",
    width: "140px",
  },
];

const loading = computed(() => {
  return (
    props.task.requestMap.listRequest.loading.value ||
    props.task.requestMap.createTaskRequest.loading.value ||
    props.options.state.optionsLoading.value
  );
});

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

const showList = computed(() => {
  console.log("props.task.state.listData", props.task.state.listData);
  const { page, size } = state.pageParams;
  const start = (page - 1) * size;
  const end = page * size;
  const listSlice = state.list.slice(start, end);
  return listSlice;
});

// 表格选中配置
const rowSelection = {
  selectedRowKeys: state.selectedRowKeys,
  onSelect: (record: Record<string, any>, selected: boolean) => {
    const { id } = record;
    console.log("record", record);
    const i = state.selectedRowKeys.indexOf(id);
    if (i >= 0) {
      state.selectedRowKeys.splice(i, 1);
    } else {
      state.selectedRowKeys.push(id);
    }
    console.log("selectIds", state.selectedRowKeys);
    // console.log("state.selectedRowKeys", state.selectedRowKeys);
  },
  onSelectAll: (selected: boolean) => {
    if (selected) {
      state.selectedRowKeys = state.list.map((item: Record<string, any>) => item.id);
    } else {
      state.selectedRowKeys = [];
    }
    console.log("selectIds", state.selectedRowKeys);
  },
};

// 操作区
const operateList = [
  {
    name: "新建任务",
    icon: "plus",
    key: "add",
    customClass: "custom-btn",
  },
];

const taskFormModalRef = ref();

// 导出
const onAdd = () => {
  taskFormModalRef.value.onOpen();
};

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

// 获取列表
const getList = async () => {
  props.task.api.getTaskList();
};

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);
      // // resolve(res)
      // if (res?.code == 200) {
      //   await getList();
      // }
      // return res;
    },
    onCancel() {},
  };
};

const onShowDelete = async (info: Record<string, any>) => {
  const res = await props.task.api.onShowTaskDelete(info.id);
  console.log("onShowDelete", res);
  if (res?.code == 200) {
    props.task.api.getTaskList();
  }
};

// 分页
const onPageChange = async (options: Record<string, any>) => {
  const { current, pageSize } = options;
  state.pageParams.page = current;
  state.pageParams.size = pageSize;
  // await getList();
};

const navigator = (options: Record<string, any>) => {
  const { path, params } = options;
  router.push({
    path,
    query: params,
  });
};

// 初始化
const init = () => {};

onMounted(() => {
  init();
});

const prefix = "data-import";
</script>

<template>
  <div :class="prefix">
    <ModuleCard title="训练任务">
      <template #head-extra>
        <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>
        </Space>
      </template>
      <div>
        <Table
          :loading="loading"
          rowKey="id"
          :dataSource="showList"
          :columns="columns"
          :pagination="{
            showSizeChanger: true,
            total: props.task.state.listData.value.length,
            pageSize: state.pageParams.size,
            current: state.pageParams.page,
          }"
          @change="onPageChange"
        >
          <template #bodyCell="{ column, text, index, record }">
            <template v-if="['createTime', 'markerTime'].includes(column.dataIndex as string)">
              {{ dayjs(text).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
            <!-- 名称 -->
            <template v-if="column.dataIndex === 'model_name'">
              <a
                @click="
                  navigator({
                    path: `/model-training/detail`,
                    params: {
                      id: record.id,
                    },
                  })
                "
              >
                {{ text }}</a
              >
            </template>
            <template v-if="column.dataIndex === 'status'">
              <Tag :color="statusColorMap[text]">{{ statusMap[text] }}</Tag>
            </template>
            <!-- 编辑 -->
            <template v-if="column.dataIndex === 'operate'">
              <Space :size="10">
                <a
                  @click="
                    navigator({
                      path: `/model-training/detail`,
                      params: {
                        id: record.id,
                      },
                    })
                  "
                >
                  查看
                </a>
                <a class="delete-link" @click="onShowDelete(record)"> 删除 </a>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </ModuleCard>
  </div>
  <TaskFormModal ref="taskFormModalRef" v-bind="props" @onSuccess="getList" />
</template>

<style lang="scss" scoped>
$prefix: "data-import";

.#{$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;
  }
  .marker-row {
    width: 100%;
    max-width: 500px;
    display: flex;
    align-items: center;
    justify-self: start;
    gap: 10px;
    height: 33px;
    &:hover {
      .marker-edit {
        display: block;
      }
    }
  }
  .delete-link {
    color: #dd524c;
  }
  :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>
