<template>
  <div>
    <PlusPage
      :columns="tableConfig"
      :request="getList"
      :before-search-submit="handleBeforeSearch"
      :is-card="true"
      :table="{
        isSelection: true,
        actionBar: { buttons, type: 'button', width: 240 },
        adaptive: { offsetBottom: 50 },
        onSortChange: handleSortChange,
        onSelectionChange: handleSelect
      }"
      :defaultPageInfo="{ page: 1, pageSize: 10 }"
      :defaultPageSizeList="[10, 20, 50, 100]"
    >
      <template #table-title>
        <el-row class="button-row">
          <el-button type="primary" @click="handleCreate"> 添加</el-button>
          <el-button type="danger" @click="handleBatchDelete">
            批量删除
          </el-button>
        </el-row>
      </template>
      <template #table-toolbar>
        <ExportView
          title="导出"
          url="''"
          file-name="订单列表"
          :query-params="{}"
        />
      </template>
    </PlusPage>
    <!-- 弹窗编辑 -->
    <PlusDialogForm
      ref="dialogForm"
      v-model:visible="visible"
      :form="{
        columns,
        labelPosition: 'top',
        rules,
        rowProps: { gutter: 20 },
        colProps: { span: 12 }
      }"
      :dialog="{ title: dialogTitle + '用户组', width: 800, confirmLoading }"
      @change="handleChange"
      @confirm="handleSubmit"
      @submit-error="handleSubmitError"
      @close="handleClose"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, toRefs } from "vue";
import {
  type PageInfo,
  type PlusColumn,
  type FieldValues,
  PlusDialogForm,
  PlusPage,
  useTable
} from "plus-pro-components";
import { cloneDeep } from "lodash";
import { ElMessage } from "element-plus";
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: Number((Math.random() * 100).toFixed(2)),
      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(), new Date()].join(" - "),
      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);
  });

  console.log(pageList);

  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 dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));
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 <= 30
        ? { status: "exception" }
        : value > 30 && value <= 50
          ? { status: "warning" }
          : { status: "success" };
    },
    minWidth: 180
  },
  {
    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: 120
  },
  {
    label: "时间段",
    prop: "timeRange",
    valueType: "date-picker",
    fieldProps: {
      type: "datetimerange",
      startPlaceholder: "请选择开始时间",
      endPlaceholder: "请选择结束时间",
      valueFormat: "YYYY-mm-DD HH:mm:ss",
      disabledDate: disabledDate,
      onCalendarChange: calendarChange
    },
    hideInTable: true,
    tableColumnProps: {
      sortable: false
    },
    minWidth: 120
  }
];

/*--------------------表单--------------------*/

const dialogVisible = ref(false);

const dialogForm = ref(null);

const state = reactive<FieldValues>({
  status: "0",
  name: "",
  rate: 4,
  isCreate: true,
  progress: 100,
  confirmLoading: false,
  switch: true,
  time: new Date().toString(),
  img: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
  query: { groupName: "" },
  currentRow: {},
  visible: false,
  detailsVisible: false,
  isBatch: false,
  selectedIds: [],
  form: {
    groupName: "",
    remark: "",
    userGroupId: undefined
  },
  rules: {
    name: [
      {
        required: true,
        message: "请输入",
        trigger: "blur"
      }
    ]
  }
});

const columns: PlusColumn[] = [
  {
    label: "名称",
    width: 120,
    prop: "name",
    valueType: "copy",
    tooltip: "名称最多显示6个字符"
  },
  {
    label: "状态",
    width: 120,
    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: "标签",
    width: 120,
    prop: "tag"
  },
  {
    label: "执行进度",
    width: 200,
    prop: "progress"
  },
  {
    label: "评分",
    width: 200,
    prop: "rate",
    valueType: "rate"
  },
  {
    label: "是否显示",
    width: 100,
    prop: "switch",
    valueType: "switch"
  },
  {
    label: "图片",
    prop: "img",
    width: 100,
    valueType: "img"
  },
  {
    label: "时间",
    prop: "time",
    valueType: "date-picker"
  },
  {
    label: "数量",
    prop: "number",
    valueType: "input-number",
    fieldProps: { precision: 2, step: 2 }
  },
  {
    label: "城市",
    prop: "city",
    valueType: "cascader",
    options: [
      {
        value: "0",
        label: "陕西",
        children: [
          {
            value: "0-0",
            label: "西安",
            children: [
              {
                value: "0-0-0",
                label: "新城区"
              },
              {
                value: "0-0-1",
                label: "高新区"
              },
              {
                value: "0-0-2",
                label: "灞桥区"
              }
            ]
          }
        ]
      },
      {
        value: "1",
        label: "山西",
        children: [
          {
            value: "1-0",
            label: "太原",
            children: [
              {
                value: "1-0-0",
                label: "小店区"
              },
              {
                value: "1-0-1",
                label: "古交市"
              },
              {
                value: "1-0-2",
                label: "万柏林区"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    label: "地区",
    prop: "place",
    tooltip: "请精确到门牌号",
    fieldProps: {
      placeholder: "请精确到门牌号"
    }
  },
  {
    label: "要求",
    prop: "demand",
    valueType: "checkbox",
    options: [
      {
        label: "四六级",
        value: "0"
      },
      {
        label: "计算机二级证书",
        value: "1"
      },
      {
        label: "普通话证书",
        value: "2"
      }
    ]
  },
  {
    label: "梦想",
    prop: "gift",
    valueType: "radio",
    options: [
      {
        label: "诗",
        value: "0"
      },
      {
        label: "远方",
        value: "1"
      }
    ]
  },
  {
    label: "到期时间",
    prop: "endTime",
    valueType: "date-picker",
    fieldProps: {
      type: "datetimerange",
      startPlaceholder: "请选择开始时间",
      endPlaceholder: "请选择结束时间"
    }
  },
  {
    label: "说明",
    prop: "desc",
    valueType: "textarea",
    fieldProps: {
      maxlength: 10,
      showWordLimit: true,
      autosize: { minRows: 2, maxRows: 4 }
    }
  }
];

// 创建
const handleCreate = (): void => {
  state.currentRow = {};
  state.form = {
    groupName: "",
    remark: "",
    userGroupId: undefined
  };
  state.isCreate = true;
  state.visible = true;
};

// 批量删除
const handleBatchDelete = async () => {
  console.log("批量删除");
  if (!state.selectedIds.length) {
    ElMessage.warning("请选择数据！");
    return;
  }
  console.log(state.selectedIds);
};
// 选择
const handleSelect = (data: any) => {
  state.selectedIds = [...data].map(item => item.id);
};
const handleChange = (values: FieldValues) => {
  console.log(values, "change");
};
const handleSubmit = (values: FieldValues) => {
  console.log(values, "Submit");
  confirmLoading.value = true;
  setTimeout(() => {
    confirmLoading.value = false;
    visible.value = false;
  }, 2000);
};
const handleSubmitError = (err: any) => {
  console.log(err, "err");
};
const handleClose = () => {
  // 重置表单
  dialogForm.value.formInstance.resetFields();
};

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: "确定删除此数据吗？"
      }
    }
  }
];

const { form, confirmLoading, rules, currentRow, visible, detailsVisible } =
  toRefs(state);
</script>
