<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 ImportModal from "@/views/dataManage/index/components/Modal/ImportModal.vue";
import ImportEditModal from "@/views/dataManage/index/components/Modal/importEditModal.vue";
import ModuleCard from "@/views/dataManage/index/components/Card/ModuleCard.vue";
import { ref, h, unref, computed, watch, reactive, onMounted } from "vue";
import { Button, Spin, message, Modal, Space, Tooltip, Input } from "ant-design-vue";
import Table from "@/views/dataManage/index/components/Table/index.vue";
import { useMain } from "@/views/dataManage/index/hooks/mock.ts";
import dayjs from "dayjs";
import DataExport from "@/views/dataManage/index/components/Module/DataExport.vue";
import ExportModal from "@/views/dataManage/index/components/Modal/ExportModal.vue";

interface PropsType {
  common: Record<string, any>;
  statistics: Record<string, any>;
  dataExport: Record<string, any>;
  dataImport: Record<string, any>;
  dataset: Record<string, any>;
  // data: Record<string, any>[];
}

const props = withDefaults(defineProps<PropsType>(), {
  common: () => {
    return {};
  },
  dataset: () => {
    return {};
  },
  statistics: () => {
    return {};
  },
  dataExport: () => {
    return {};
  },
  dataImport: () => {
    return {};
  },
  // state: () => {
  //   return {};
  // },
  // api: () => {
  //   return {};
  // },
  // requestMap: () => {
  //   return {};
  // },
});

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

const { generatorList, sleep } = useMain();

// 表头
const columns = [
  {
    title: "数据名称",
    dataIndex: "batch_name",
    width: "15%",
  },
  {
    title: "数据来源",
    dataIndex: "batch_id",
    width: "10%",
  },
  {
    title: "数据描述",
    dataIndex: "description",
    width: "10%",
  },
  {
    title: "总数量",
    dataIndex: "point_count",
    width: "7%",
  },
  {
    title: "雷达工作模式",
    dataIndex: "work_mode",
    width: "15%",
  },
  {
    title: "雷达系统参数",
    dataIndex: "system_param",
    width: "15%",
  },
  {
    title: "系统状态",
    dataIndex: "system_status",
    width: "15%",
  },
  // {
  //   title: "标注时间",
  //   dataIndex: "timestamp",
  //   width: "15%",
  // },
  {
    title: "数据大小",
    dataIndex: "size_mb",
    width: "8%",
  },
  {
    title: "操作",
    dataIndex: "operate",
    width: "5%",
  },
];

const calcList = (list: Record<string, any>[]) => {
  const { page, size } = state.pageParams;
  const start = (page - 1) * size;
  const end = page * size;
  return list.slice(start, end);
};

const loading = computed(() => {
  return props.dataImport.requestMap.listRequest.loading.value;
});

// 表格配置项
const state = reactive<TableOptions>({
  loading: loading.value, // 是否在请求
  selectedRowKeys: [], // 选中的数据
  list: props.dataImport.state.importData, // 列表
  total: props.dataImport.state.importData.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.dataImport.state.importData.value
    .slice(start, end)
    .map((item: Record<string, any>) => {
      return {
        ...item,
        children: [...(item?.children || [])],
      };
    });
  return listSlice;
});

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

// 操作列表
const operateList = [
  {
    name: "导出数据",
    icon: "export",
    key: "export",
    customClass: "custom-btn",
    disabled: false,
  },
  {
    name: "导入数据",
    icon: "import",
    key: "import",
    customClass: "custom-btn",
  },
  // {
  //   name: "接收数据",
  //   icon: "refresh",
  //   key: "receive",
  //   customClass: "custom-btn grey-btn",
  // },
  // {
  //   name: "保存标注",
  //   icon: "save",
  //   key: "save",
  //   customClass: "custom-btn grey-btn",
  // },
];

const showOperateList = computed(() => {
  return operateList.map((item) => {
    const newItem = { ...item };
    if (newItem.key === "export") {
      newItem.disabled = selectDataIds.value.length === 0;
    }
    return newItem;
  });
});

// 选中的数据集合
const selectDataIds = ref([]);

const exportModalRef = ref();

// 导出
const exportData = () => {
  exportModalRef.value.onOpen(unref(selectDataIds));
};

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

// 接收
const onReceive = () => {};

// 导入弹出层
const importModalRef = ref();

// 显示导入弹窗
const onShowImpotModal = () => {
  importModalRef.value.onOpen();
};

// 导入编辑弹出层
const importEditModalRef = ref();

// 显示导入弹窗
const onShowImpotEditModal = (info: Record<string, any>) => {
  importEditModalRef.value.onOpen(info);
};

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

// 开启编辑的索引
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.batch_id,
    name: info.batch_name,
    description: info.description,
  };
  console.log("info", info, props);
  const res = await props.dataImport.api.onUpdate(params);
  if (res?.code == 200) {
    message.success("修改成功");
  }
  await getList();
};

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

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 = (info: Record<string, any>) => {
  const modalProps = createDeleteProps(info);
  Modal.confirm(modalProps);
};

const deleteLoading = ref(false);

const onDelete = async (info: Record<string, any>) => {
  console.log("onDelete", info, props);
  const res = await props.dataImport.api.onDelete({
    fileName: info.batch_id,
  });

  return res;
};

// 更新数据集
const updateDataset = () => {
  props.dataset.api.getTestDataset();
  props.dataset.api.getTrainDataset();
};

const afterImport = () => {
  getList();
  updateDataset();
  // props.dataExport.api.getExportData();
};

const expendLoadingList = ref<boolean[]>([]);

const getLoadingById = (id: string) => {
  const i = props.dataImport.state.importData.value.findIndex((v: Record<string, any>) => {
    return v.batch_id == id;
  });
  console.log("getLoadingById", id, i, expendLoadingList.value[i]);
  return expendLoadingList.value[i] || false;
};

// 展开变化
const onExpandChange = async (expanded: boolean, record: Record<string, any>) => {
  console.log("onExpandChange", expanded, record);
  if (!expanded) return;
  const i = props.dataImport.state.importData.value.findIndex((v: Record<string, any>) => {
    return v.batch_id == record.batch_id;
  });
  if (i == -1) return;
  expendLoadingList.value[i] = true;
  const res = await props.dataExport.api.getExportData({
    record_id: record.batch_id,
  });
  props.dataImport.state.importData.value[i].children = res.data;
  expendLoadingList.value[i] = false;
};

// 更新导出数据
const updateExportList = async (e: Record<string, any>) => {
  const { even, row } = e;
  const params: Record<string, any> = {
    record_id: row.batch_id,
  };
  if (even.date_str) {
    params.date_str = even.date_str;
  }
  if (even.date_str) {
    params.date_str = even.date_str;
  }
  if (even.track_id) {
    params.track_id = even.track_id;
  }
  const i = props.dataImport.state.importData.value.findIndex((v: Record<string, any>) => {
    return v.batch_id == row.batch_id;
  });
  expendLoadingList.value[i] = true;
  console.log("i", i);

  const res = await props.dataExport.api.getExportData(params);
  if (res?.code == 200) {
    if (i != -1) {
      props.dataImport.state.importData.value[i].children = res.data;
    }
  }
  expendLoadingList.value[i] = false;
};

onMounted(() => {});

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

<template>
  <div :class="prefix" v-bind="$attrs">
    <ModuleCard title="数据导入">
      <template #head-extra>
        <Space :size="20">
          <Button
            type="primary"
            v-for="item in showOperateList"
            :disabled="item.disabled"
            :class="item.customClass"
            @click="onMenuSelect(item)"
          >
            <template #icon>
              <Icon :name="item.icon" />
            </template>
            {{ item.name }}
          </Button>
        </Space>
      </template>
      <div>
        <Table
          :class="`${prefix}-table`"
          :loading="loading"
          rowKey="batch_id"
          :dataSource="showList"
          :columns="columns"
          :showExpand="true"
          :pagination="{
            showSizeChanger: true,
            total: props.dataImport.state.importData.value.length,
            pageSize: state.pageParams.size,
            current: state.pageParams.page,
          }"
          @change="onPageChange"
          @expand="onExpandChange"
        >
          <template #bodyCell="{ column, text, index, record }">
            <!-- 数据名称 -->
            <template v-if="['batch_id'].includes(column.dataIndex)">
              <Tooltip :title="text">
                <div class="marker-text">
                  {{ text }}
                </div>
              </Tooltip>
            </template>
            <template
              v-if="
                [
                  'batch_name',
                  'description',
                  'point_count',
                  'work_mode',
                  'system_param',
                  'system_status',
                ].includes(column.dataIndex)
              "
            >
              <div 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': true,
                  'marker-row-limit': 'batch_name' == column.dataIndex,
                }"
                v-else
                @click="onShowImpotEditModal(record)"
              >
                <Tooltip :title="text">
                  <div class="marker-text">
                    {{ text }}
                  </div>
                </Tooltip>
              </div>
            </template>
            <!-- 时间格式化 -->
            <template v-if="['createTime', 'timestamp'].includes(column.dataIndex as string)">
              {{ dayjs(text).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
            <!-- 数据描述 -->

            <template v-if="column.dataIndex === 'size_mb'">
              <Tooltip :title="`${text}MB`">
                <div class="marker-text">{{ text }} MB</div>
              </Tooltip>
            </template>
            <!-- 编辑 -->
            <template v-if="column.dataIndex === 'operate'">
              <Space :size="10">
                <Tooltip title="删除" class="delete-btn">
                  <Button type="text" @click="onShowDelete(record)">
                    <template #icon>
                      <Icon name="delete" />
                    </template>
                  </Button>
                </Tooltip>
              </Space>
            </template>
            <!-- 展开 -->
          </template>
          <template #expandedRowRender="{ record, index }">
            <DataExport
              v-bind="{
                api: props.dataExport.api,
                requestMap: props.dataExport.requestMap,
                state: props.dataExport.state,
                list: record.children,
                loading: getLoadingById(record.batch_id),
                recordId: record.batch_id,
              }"
              v-model:selectDataIds="selectDataIds"
              @updateList="
                updateExportList({
                  row: record,
                  even: $event,
                })
              "
              @updateDataset="updateDataset"
            />
          </template>
        </Table>
      </div>
    </ModuleCard>
  </div>
  <ExportModal
    ref="exportModalRef"
    @onSuccess="updateDataset"
    v-bind="{
      api: props.dataExport.api,
      requestMap: props.dataExport.requestMap,
      state: props.dataExport.state,
    }"
  />
  <ImportModal
    ref="importModalRef"
    @onSuccess="afterImport"
    v-bind="{
      api: props.dataImport.api,
      state: props.dataImport.state,
      requestMap: props.dataImport.requestMap,
    }"
  />
  <ImportEditModal
    ref="importEditModalRef"
    @onSuccess="afterImport"
    v-bind="{
      api: props.dataImport.api,
      state: props.dataImport.state,
      requestMap: props.dataImport.requestMap,
    }"
  />
</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;
  }
  .edit-btn {
    color: #3662e3;
  }
  .delete-btn {
    color: #dd524c;
  }
  .marker-row {
    width: 100%;
    height: 100%;
    max-width: 500px;
    display: flex;
    align-items: center;
    justify-self: start;
    gap: 10px;
    &:hover {
      .marker-edit {
        display: block;
      }
    }
    &-limit {
      width: calc(100% - 50px);
    }
  }
  .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;
    }
  }
  :deep(.ant-spin-nested-loading) {
    &::-webkit-scrollbar {
      display: none;
    }
  }
}
</style>
