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

<script setup lang="ts">
import Icon from "@/components/Module/Icon/index.vue";
import ImportDataLabelModal from "@/views/dataManage/index/components/Modal/ImportDataLabelModa.vue";
import ModuleCard from "@/views/dataManage/index/components/Card/ModuleCard.vue";
import { ref, Ref, unref, computed, watch, reactive, onMounted } from "vue";
import Table from "@/views/dataManage/index/components/Table/index.vue";
import { Button, Space, message, Select, SelectOption, Input, Spin } from "ant-design-vue";
import dayjs from "dayjs";
import ExportModal from "@/views/dataManage/index/components/Modal/ExportModal.vue";
import _ from "lodash";

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

interface PropsType {
  state: Record<string, any>;
  api: Record<string, any>;
  requestMap: Record<string, any>;
  list: Record<string, any>[];
  loading: boolean;
  recordId: string;
  selectDataIds: string[];
}

const props = withDefaults(defineProps<PropsType>(), {
  state: () => {
    return {};
  },
  api: () => {
    return {};
  },
  requestMap: () => {
    return {};
  },
  list: () => {
    return [];
  },
  loading: false,
  recordId: "",
  selectDataIds: () => {
    return [];
  },
});

const emits = defineEmits(["updateList", "updateDataset", "update:selectDataIds"]);

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

// 表头
const columns = [
  {
    title: "批号",
    dataIndex: "track_id",
    ellipsis: true,
    width: "20%",
  },
  {
    title: "导入时间",
    dataIndex: "timestamp",
    width: "20%",
  },
  {
    title: "真值标注",
    dataIndex: "label_info",
    width: "20%",
  },
  {
    title: "标注时间",
    dataIndex: "label_time",
    width: "20%",
  },
  {
    title: "标注人",
    dataIndex: "label_man",
    width: "10%",
  },
];

const searchForm = ref({
  date_str: null,
  track_id: null,
  label_info: null,
});

const onDateChange = (e: string | any, ...args: any) => {
  state.pageParams.page = 1;
  _.debounce(() => {
    updateList();
  }, 1000)();
  // props.api.onExportDataSearch();
};

const onLabelInfoChange = (e: string | any, ...args: any) => {
  state.pageParams.page = 1;
  _.debounce(() => {
    updateList();
  }, 1000)();

  // props.api.onExportDataSearch();
};

const useList = ref([]);

watch(
  () => props.list,
  (val) => {
    useList.value = val;
  },
);

// const loading = computed(() => {
//   return props.loading;
// });

// 表格配置项
const state = reactive<TableOptions>({
  loading: props.loading, // 是否在请求
  selectedRowKeys: [], //
  list: unref(useList), // 列表
  total: unref(useList).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 = unref(useList).slice(start, end);
  return listSlice;
});

let colSelectIds = computed(() => props.selectDataIds);

// 表格选中配置
const rowSelection = {
  selectedRowKeys: colSelectIds,
  onSelect: (record: Record<string, any>, selected: boolean) => {
    const useList = JSON.parse(JSON.stringify(props.selectDataIds));
    const { track_id } = record;
    const i = props.selectDataIds.indexOf(track_id);
    if (i >= 0) {
      useList.splice(i, 1);
    } else {
      useList.push(track_id);
    }
    emits("update:selectDataIds", useList);
  },
  onSelectAll: (selected: boolean) => {
    let useList = JSON.parse(JSON.stringify(props.selectDataIds));
    showList.value.forEach((item: Record<string, any>) => {
      const i = useList.indexOf(item.track_id);
      if (selected) {
        if (i < 0) {
          useList.push(item.track_id);
        }
      } else {
        if (i >= 0) {
          useList.splice(i, 1);
        }
      }
    });
    emits("update:selectDataIds", useList);

    // if (selected) {
    //   // useList = showList.value.map((item: Record<string, any>) => item.track_id);
    // } else {
    //   useList = [];
    // }
    // emits("update:selectDataIds", useList);
    // console.log("useList", props.selectDataIds);
  },
};

// 操作区
const operateList = [
  {
    name: "数据集全选/全不选",
    icon: "chat",
    key: "selectAll",
    customClass: "custom-btn",
    disabled: false,
  },
  {
    name: "导入标注",
    icon: "import",
    key: "import",
    customClass: "custom-btn",
    disabled: false,
  },
];

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

const exportModalRef = ref();

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

const onToggleSelectAllData = () => {
  const useListIds = useList.value.map((item) => item.track_id);
  let selectDataIds = JSON.parse(JSON.stringify(props.selectDataIds));
  const isSelectAll = useListIds.every((item) => {
    return selectDataIds.includes(item);
  });
  console.log("isSelectAll", isSelectAll);
  if (isSelectAll) {
    selectDataIds = selectDataIds.filter((item) => !useListIds.includes(item));
  } else {
    useListIds.forEach((item) => {
      if (!selectDataIds.includes(item)) {
        selectDataIds.push(item);
      }
    });
  }
  emits("update:selectDataIds", selectDataIds);
};

const importDataLabelModalRef = ref();

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

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

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

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

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

// 设置编辑的索引
const onSetEditIndex = (number: number) => {
  console.log("onSetEditIndex", number);
  editIndex.value = number;
  if (number == -1) {
    editText.value = "";
  } else {
    editText.value = unref(showList)[number].label_info;
  }
};

// 更新数据
const onUpdate = async (info: Record<string, any>) => {
  const params = {
    id: info.track_id,
    label: info.new_label_info,
    label_man: info.label_man,
  };
  await props.api.onUpdateLabel(params);
  updateList();
  // await props.api.getExportData();
};

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

// 获取数据
const updateList = () => {
  emits("updateList", searchForm.value);
};

// 获取数据集数据
const updateDataset = () => {
  console.log("updateDataset");
  emits("updateDataset");
};

// 导出后更新数据
const afterExport = () => {};

onMounted(() => {});

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

<template>
  <div :class="prefix">
    <ModuleCard title="">
      <template #head-extra>
        <Space :size="20">
          <Button
            type="primary"
            v-for="item in showOperateList"
            :class="item.customClass"
            :disabled="item.disabled"
            @click="onMenuSelect(item)"
          >
            <template #icon>
              <Icon :name="item.icon" />
            </template>
            {{ item.name }}
          </Button>
        </Space>
      </template>
      <div @click.stop>
        <!--
          :loading="state.loading"
         -->
        <Table
          :loading="props.loading"
          rowKey="track_id"
          :rowSelection="rowSelection"
          :dataSource="showList"
          :columns="columns"
          :pagination="{
            showSizeChanger: true,
            total: useList.length,
            pageSize: state.pageParams.size,
            current: state.pageParams.page,
            pageSizeOptions: ['5', '10', '20', '50', '100'],
          }"
          @change="onPageChange"
        >
          <template #headerCell="{ title, column }">
            <template v-if="column.dataIndex == 'track_id'">
              <div :class="`${prefix}-table-header-cell`">
                <div :class="`${prefix}-table-header-cell-label`">批号</div>
                <Input
                  :allow-clear="true"
                  placeholder="请输入批次时间"
                  v-model:value="searchForm.track_id"
                  @change="onDateChange"
                  style="margin-left: 20px"
                />
              </div>
            </template>
            <template v-if="column.dataIndex == 'label_info'">
              <div :class="`${prefix}-table-header-cell`">
                <div :class="`${prefix}-table-header-cell-label`">真值标注</div>
                <Input
                  :allow-clear="true"
                  placeholder="请输入真值标注"
                  v-model:value="searchForm.label_info"
                  @change="onLabelInfoChange"
                  style="margin-left: 20px"
                />
              </div>
            </template>
          </template>
          <template #bodyCell="{ column, text, index, record }">
            <template v-if="['label_time', 'timestamp'].includes(column.dataIndex as string)">
              {{ dayjs(text).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
            <!-- 真值标注 -->
            <template v-if="column.dataIndex === 'label_info'">
              <div class="marker-row" v-if="editIndex == index">
                <div class="marker-input">
                  <Input :value="editText" @change="onUpdateEditText" />
                </div>
                <div class="marker-operate">
                  <Space>
                    <Button
                      type="text"
                      @click="
                        afterEdit({
                          ...record,
                          new_label_info: 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)">
                <div class="marker-text">{{ text }}</div>
              </div>
            </template>
          </template>
        </Table>
      </div>
    </ModuleCard>
    <ExportModal ref="exportModalRef" @onSuccess="updateDataset" v-bind="props" />
    <ImportDataLabelModal ref="importDataLabelModalRef" @onSuccess="updateList" v-bind="props" />
  </div>
</template>

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

.#{$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;
      }
    }
  }
  &-table {
    &-header {
      &-cell {
        display: flex;
        align-items: center;
        &-label {
          flex-shrink: 0;
        }
      }
    }
  }
  :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>
