<template>
  <div>
    <PlusPage
      :columns="tableConfig"
      :request="getList"
      :before-search-submit="handleBeforeSearch"
      :is-card="true"
      :table="{
        onSortChange: handleSortChange,
        isSelection: true,
        actionBar: { buttons, type: 'button', width: 240 },
        adaptive: { offsetBottom: 50 }
      }"
      :defaultPageInfo="{ page: 1, pageSize: 10 }"
      :defaultPageSizeList="[10, 20, 50, 100]"
    >
      <template #toolbar>
        <ExportView
          title="导出"
          url="''"
          file-name="订单列表"
          :query-params="{}"
        />
      </template>
    </PlusPage>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineOptions, ref } from "vue";
import {
  type PageInfo,
  type PlusColumn,
  PlusPage,
  useTable
} from "plus-pro-components";
import { cloneDeep } from "lodash-es";
import { number } from "echarts";

import ExportView from "@/components/ExportView/index.vue";

defineOptions({
  name: "PageTable"
});

interface TableRow {
  id: number;
  name: string;
  status: string;
  tag: string;
  time: Date;
}

const getList = async (
  query: PageInfo & {
    status?: string;
    name?: string;
  }
) => {
  const { page = 1, pageSize = 20, status, name } = query || {};
  const total = 100;
  const List = Array.from({ length: total }).map((_, index) => {
    return {
      id: index,
      name: index === 0 ? "name".repeat(99) : index + "name",
      status: String(index % 3),
      tag:
        index === 1
          ? "success"
          : index === 2
            ? "warning"
            : index === 3
              ? "info"
              : "danger",
      progress: 10,
      rate: index > 3 ? 2 : 3.5,
      switch: index % 2 === 0,
      img: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      time: new Date(),
      timeRange: new Date(),
      custom: "custom" + index
    };
  });

  const mockList = List.filter(item => {
    if (status && status !== item.status) {
      return false;
    }
    return !(name && name !== item.name);
  });

  const pageList = mockList.filter(
    (_, index) => index < pageSize * page && index >= pageSize * (page - 1)
  );

  // 等待2s
  await new Promise(resolve => {
    setTimeout(() => {
      resolve("");
    }, 500);
  });

  return { data: pageList, success: true, total: mockList.length };
};

// 搜索之前函数
const handleBeforeSearch = (values: any) => {
  const params = cloneDeep(values);
  Reflect.set(params, "name1", Reflect.get(values, "name"));
  Reflect.deleteProperty(params, "name");
  console.log(params);

  // 返回新的参数
  return params;
};

const handleSortChange = (val: object) => {
  console.log("handleSortChange", val);
};

const choiceDate = ref(null);

const disabledDate = (time: any) => {
  // 如何选择了一个日期
  if (choiceDate.value) {
    // 7天的时间戳
    const one = 30 * 24 * 3600 * 1000;
    // 当前日期 - one = 7天之前
    const minTime = choiceDate.value - one;
    // 当前日期 + one = 7天之后
    const maxTime = choiceDate.value + one;
    return (
      time.getTime() < minTime || time.getTime() > maxTime
      // 限制不能选择今天及以后
      // || time.getTime() + 1 * 24 * 3600 * 1000 > Date.now()
    );
  } else {
    // 如果没有选择日期，就要限制不能选择今天及以后
    // return time.getTime() + 1 * 24 * 3600 * 1000 > Date.now();
  }
};

const calendarChange = (obj: any) => {
  console.log(obj);
  const minDate = obj[0];
  const maxDate = obj[1];
  // 把选择的第一个日期赋值给一个变量。
  choiceDate.value = minDate.getTime();
  // 如何你选择了两个日期了，就把那个变量置空
  if (maxDate) choiceDate.value = null;
};

const { buttons } = useTable<TableRow[]>();

const tableConfig: PlusColumn[] = [
  {
    label: "名称",
    tooltip: "名称最多显示6个字符",
    prop: "name",
    tableColumnProps: {
      showOverflowTooltip: true
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "未解决",
        value: "0",
        color: "red"
      },
      {
        label: "已解决",
        value: "1",
        color: "blue"
      },
      {
        label: "解决中",
        value: "2",
        color: "yellow"
      },
      {
        label: "失败",
        value: "3",
        color: "red"
      }
    ]
  },
  {
    label: "标签",
    prop: "tag",
    valueType: "tag",
    fieldProps: (value: string) => {
      return { type: value };
    }
  },
  {
    label: "执行进度",
    prop: "progress",
    valueType: "progress",
    fieldProps: (value: number) => {
      return value === 0
        ? { status: "exception" }
        : value > 5
          ? { status: "warning" }
          : value > 3
            ? { status: "success" }
            : { status: "exception" };
    }
  },
  {
    label: "评分",
    prop: "rate",
    valueType: "rate",
    hideInSearch: true,
    editable: true,
    minWidth: 130
  },
  {
    label: "开关",
    prop: "switch",
    hideInSearch: true,
    valueType: "switch",
    editable: true,
    maxWidth: 100,
    minWidth: 40
  },
  {
    label: "时间",
    prop: "time",
    valueType: "date-picker",
    hideInForm: true,
    fieldProps: {
      valueFormat: "YYYY-mm-DD HH:mm:ss"
    },
    tableColumnProps: {
      sortable: true
    },
    minWidth: "180px"
  },
  {
    label: "时间段",
    prop: "timeRange",
    valueType: "date-picker",
    fieldProps: {
      type: "datetimerange",
      startPlaceholder: "请选择开始时间",
      endPlaceholder: "请选择结束时间",
      valueFormat: "YYYY-mm-DD HH:mm:ss",
      disabledDate: disabledDate,
      onCalendarChange: calendarChange
    },
    hideInForm: true,
    tableColumnProps: {
      sortable: false
    },
    minWidth: "180px"
  }
];

buttons.value = [
  {
    // 查看
    text: "查看",
    code: "view",
    props: (row: any) => ({
      type: "info",
      disabled: row.status === "1"
    }),
    show: (row: any) => row.status === "1"
  },
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: (row: any) => ({
      type: "primary",
      disabled: row.status === "1"
    }),
    show: computed(() => true)
  },
  {
    // 删除
    text: "删除",
    code: "delete",
    // props v0.1.16 版本新增计算属性支持
    props: computed(() => ({ type: "danger" })),
    confirm: {
      options: {
        draggable: true,
        message: "确定删除此数据吗？"
      }
    }
  }
];
</script>
