<template>
  <Modal
    width="800px"
    title="媒体库"
    :open="visible"
    @ok="okHandler"
    :afterClose="afterClose"
    @cancel="emit('update:visible', false)"
    okText="确定"
    cancelText="取消"
    class="model-table"
  >
    <div>
      <div className="model-header">
        <p class="header-desc">
          已选择数据<span>（ {{ rowSelection.selectedRowKeys.length }} ）</span>
        </p>
        <div class="up-se">
          <span class="upload fun-ctrls" v-if="!readonly">
            <ui-input
              class="input"
              :accept="ft"
              :maxSize="maxSize"
              @update:modelValue="(file: File) => uploadHandler(file)"
              type="file"
            >
              <template v-slot:replace>
                <Button type="primary" ghost>
                  <ui-icon type="add" class="icon" />上传文件
                </Button>
              </template>
            </ui-input>
          </span>
          <Search
            v-if="Object.keys(allData).length"
            className="content-header-search"
            placeholder="输入名称搜索"
            v-model:value="params.name"
            allow-clear
            style="width: 244px"
          />
          <Button
            type="primary"
            ghost
            v-if="useType === 'trace_evidence'"
            style="margin-left: 10px"
            @click="foreceRefresh"
          >
            刷新
          </Button>
        </div>
      </div>

      <div class="table-layout">
        <Table
          v-if="Object.keys(allData).length"
          :row-key="(record: Material) => record.id"
          :columns="cloumns"
          :rowSelection="rowSelection"
          :data-source="origin.list"
          :pagination="{ ...origin, current: origin.pageNum }"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <div class="name">
                <span>
                  {{ record.name }}
                </span>
              </div>
            </template>
            <template v-if="column.key === 'caseTitle'">
              <div class="name">
                <span>
                  {{ record.caseTitle || "-" }}
                </span>
              </div>
            </template>

            <template v-if="column.key === 'size'">
              {{ getSizeStr(record.size) }}
            </template>
            <template v-if="column.key === 'status'">
              {{
                record.status === 1
                  ? "上传成功"
                  : record.status === -1
                  ? "上传失败"
                  : "上传中"
              }}
            </template>
            <template v-if="column.key === 'group'">
              <span class="group-str">{{ record.group }}</span>
            </template>
            <template v-else-if="column.key === 'action'">
              <span v-if="record.useType !== 'animation'">
                <a @click="delHandler(record.id)">删除</a>
              </span>
            </template>
          </template>
        </Table>
        <div style="padding: 1px" v-else>
          <Empty
            description="暂无结果"
            :image="Empty.PRESENTED_IMAGE_SIMPLE"
            className="ant-empty ant-empty-normal"
          />
        </div>
      </div>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { Modal, Input, Table, Empty, TableProps, Button } from "ant-design-vue";
import { computed, reactive, readonly, ref, watch } from "vue";
import { createLoadPack, debounceStack, getSizeStr } from "@/utils";
import type { PagingResult } from "@/api";
import {
  addMaterial,
  delMaterial,
  fetchMaterialGroups,
  fetchMaterialPage,
  Material,
  MaterialGroup,
  MaterialPageProps,
  syncMaterialAll,
} from "@/api/material";
import Message from "bill/components/message/message.vue";
import { Dialog } from "bill/expose-common";

const props = defineProps<{
  uploadFormat?: string[];
  format?: string[];
  maxSize?: number;
  visible: boolean;
  count?: number;
  readonly?: boolean;
  groupIds: number[];
  useType?: string;
  afterClose?: () => void;
}>();

const emit = defineEmits<{
  (e: "update:visible", v: boolean): void;
  (e: "selectMaterials", v: Material[]): void;
}>();

const ft = computed(() => {
  const ft = props.uploadFormat || props.format;
  if (!ft) return void 0;
  return ft.map((t) => `.${t}`).join(",");
});

const Search = Input.Search;
const params = reactive({
  pageNum: 1,
  pageSize: 10,
  formats: props.format,
  useType: props.useType,
  groupIds: props.groupIds,
}) as MaterialPageProps;


const origin = ref<PagingResult<Material[]>>({
  list: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const groups = ref<MaterialGroup[]>([]);
// const selectKeys = ref<Material["id"][]>([]);
const allData: Record<Material["id"], Material> = reactive({});

const rowSelection = ref({
  selectedRowKeys: [] as Material["id"][],
  onChange: (ids: number[]) => {
    console.log(ids);
    const otherPageKeys = rowSelection.value.selectedRowKeys.filter(
      (key) => !origin.value.list.some((item) => key === item.id)
    );
    const newKeys = Array.from(new Set([...otherPageKeys, ...ids]));
    if (typeof props.count !== "number" || props.count >= newKeys.length) {
      rowSelection.value.selectedRowKeys = newKeys;
    } else {
      Message.error(`最多选择${props.count}项`);
    }
  },
  hideSelectAll: true,
  onSelectAll: (selected: boolean, selectedRows: Material[], changeRows: Material[]) => {
    // 显式处理全选逻辑
    console.log("全选状态变化:", selected);
  },
  getCheckboxProps: (record: Material) => {
    return {
      disabled:
        (props.format && !props.format.includes(record.format)) ||
        (props.maxSize && record.size > props.maxSize) ||
        record.status !== 1,
    };
  },
});
const cloumns = computed(() => {
  const groupIds = params.groupIds;
  const cloumns =
    props.useType === "trace_evidence"
      ? [
          {
            title: "名称",
            dataIndex: "name",
            key: "name",
          },
          {
            width: "200px",
            title: "案件",
            dataIndex: "caseTitle",
            key: "caseTitle",
          },
          {
            width: "100px",
            title: "分组",
            dataIndex: "group",
            key: "group",
            filteredValue: groupIds,
            filters: props.readonly
              ? undefined
              : groups.value.map((g) => ({
                  text: g.name,
                  value: g.id,
                })),
            // filters: groups.value.map((g) => ({
            //   text: g.name,
            //   value: g.id,
            // })),
          },
        ]
      : [
          {
            title: "名称",
            dataIndex: "name",
            key: "name",
          },
          {
            width: "100px",
            title: "格式",
            dataIndex: "format",
            key: "format",
          },
          {
            width: "100px",
            title: "大小",
            dataIndex: "size",
            key: "size",
          },
          {
            width: "100px",
            title: "状态",
            dataIndex: "status",
            key: "status",
          },
          {
            width: "100px",
            title: "分组",
            dataIndex: "group",
            key: "group",
            filteredValue: groupIds,
            filters: props.readonly
              ? undefined
              : groups.value.map((g) => ({
                  text: g.name,
                  value: g.id,
                })),
            // filters: groups.value.map((g) => ({
            //   text: g.name,
            //   value: g.id,
            // })),
          },
        ];
  if (!props.readonly) {
    cloumns.push({
      width: "100px",
      title: "操作",
      key: "action",
    } as any);
  }
  return cloumns;
});

const fetchData = createLoadPack(() =>
  Promise.all([fetchMaterialGroups(props.useType), fetchMaterialPage(params)])
);
const refresh = debounceStack(
  fetchData,
  ([group, pag]) => {
    groups.value = group;
    origin.value = pag;
    pag.list.forEach((item) => (allData[item.id] = item));
    if (pag.pageNum > 1 && pag.pageNum > Math.ceil(pag.total / pag.pageSize)) {
      params.pageNum = Math.ceil(pag.total / pag.pageSize);
      refresh();
    }
  },
  160
);

const foreceRefresh = async () => {
  await syncMaterialAll();
  await refresh();
};

const uploadHandler = async (file: File) => {
  await addMaterial(file);
  refresh();
};

watch(params, refresh, { immediate: true, deep: true });

const addHandler = async (file: File) => {
  await addMaterial(file);
  refresh();
};
const delHandler = async (id: Material["id"]) => {
  if (await Dialog.confirm("确定要删除此数据吗？")) {
    await delMaterial(id);
    const ndx = rowSelection.value.selectedRowKeys.indexOf(id);
    console.log(rowSelection.value.selectedRowKeys, id);
    if (~ndx) {
      rowSelection.value.selectedRowKeys.splice(ndx, 1);
    }
    refresh();
  }
};

const okHandler = () => {
  emit(
    "selectMaterials",
    rowSelection.value.selectedRowKeys.map((id) => allData[id])
  );
};
const handleTableChange: TableProps["onChange"] = (pag, filters) => {
  params.pageSize = pag.pageSize!;
  params.pageNum = pag.current!;
  params.groupIds = (filters.group || props.groupIds) as number[];
};
</script>

<style lang="less" scoped>
.model-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 24px;
  align-items: center;
}

.table-layout {
  max-height: 500px;
  overflow-y: auto;
}

.up-se {
  display: flex;
  align-items: center;

  .upload {
    margin-right: 10px;
    width: 100px;
    // overflow: hidden;
  }
}

.group-str {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis; //文本溢出显示省略号
  white-space: nowrap; //文本不会换行
  max-width: 200px;
}
</style>

<style lang="less">
.model-header .header-desc {
  margin-bottom: 0;
}

.ant-modal-root .ant-table-tbody > tr > td {
  word-break: break-all;
}

.content-header-search {
  flex: 1;
}

.ant-table-filter-dropdown .ant-dropdown-menu-title-content > span {
  max-width: 200px;
  overflow: hidden;
  display: inline-block;
  vertical-align: middle;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.name {
  position: relative;
  display: flex;
  align-items: center;

  span {
    position: absolute;
    max-width: 100%;
    display: block;
    overflow: hidden;
    text-overflow: ellipsis; //文本溢出显示省略号
    white-space: nowrap; //文本不会换行
  }
}
</style>
