<template>
  <!-- 表格 -->
  <ele-pro-table
    ref="tableRef"
    row-key="id"
    :columns="columns"
    :datasource="datasource"
    v-model:selection="selection"
    :customRow="customRow"
    height="calc(100vh - 390px)"
    tool-class="ele-toolbar-form"
    :scroll="{ x: 800 }"
  >
    <template #toolbar>
      <field-search
        :selection="selection"
        @search="reload"
        @add="openEdit()"
        @period="openPeriod()"
        @remove="removeBatch"
      />
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'fieldName'">
        {{ record.name }}
      </template>
      <template v-if="column.key === 'isToilet'">
        <a-tag v-if="record.isToilet == 1" color="green">是</a-tag>
        <a-tag v-else>否</a-tag>
      </template>
      <template v-if="column.key === 'isHalf'">
        <a-tag v-if="record.isHalf == 2">不可以</a-tag>
        <a-tag v-if="record.isHalf == 1" color="green">可以</a-tag>
      </template>
      <template v-if="column.key === 'isChildren'">
        <a-tag v-if="record.isChildren == 2">不支持</a-tag>
        <a-tag v-if="record.isChildren == 1" color="green">支持</a-tag>
      </template>
      <template v-if="column.key === 'isRepeat'">
        <a-tag v-if="record.isRepeat == 2">不可以</a-tag>
        <a-tag v-if="record.isRepeat == 1" color="green">可以</a-tag>
      </template>
      <template v-if="column.key === 'isStatus'">
        <a-tag v-if="record.isStatus == 2">关闭</a-tag>
        <a-tag v-if="record.isStatus == 1" color="green">开启</a-tag>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a @click="openEdit(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定要删除此场馆场地吗？"
            @confirm="remove(record)"
          >
            <a class="ele-text-danger">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </ele-pro-table>
  <!-- 编辑弹窗 -->
  <field-edit
    :data="current"
    v-model:visible="showEdit"
    :category-list="categoryList"
    :category-id="categoryId"
    @done="reload"
  />
  <!-- 时段弹窗 -->
  <PeriodEdit
    v-model:visible="showPeriodEidt"
    :category-id="categoryId"
    :data="data"
    @done="reload"
  />
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import FieldSearch from './components/field-search.vue';
  import FieldEdit from './components/fieldEdit.vue';
  import {
    pageBookingField,
    removeBookingField,
    removeBatchBookingField
  } from '@/api/booking/bookingField';
  import type {
    BookingField,
    BookingFieldParam
  } from '@/api/booking/bookingField/model';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import PeriodEdit from './period/index.vue';
  import { BookingSite } from '@/api/booking/bookingSite/model';

  const props = defineProps<{
    // 场馆场地 id
    categoryId?: number;
    // 全部分类
    categoryList: BookingSite[];
    // 当期选中
    data: BookingSite;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<any[]>([]);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    // {
    //   key: 'index',
    //   width: 48,
    //   align: 'center',
    //   fixed: 'left',
    //   hideInSetting: true,
    //   customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    // },
    {
      title: 'ID',
      width: 80,
      dataIndex: 'id'
    },
    {
      title: '场地名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '显示在第几行',
      dataIndex: 'row',
      key: 'row'
    },
    {
      title: '可重复预订次数',
      dataIndex: 'num',
      key: 'num'
    },
    {
      title: '是否是卫生间',
      dataIndex: 'isToilet',
      key: 'isToilet',
      align: 'center',
      customRender: ({ text }) => (text == true ? '否' : '是')
    },
    {
      title: '是否可预订半场',
      dataIndex: 'isHalf',
      key: 'isHalf',
      align: 'center'
    },
    {
      title: '是否支持儿童价',
      dataIndex: 'isChildren',
      key: 'isChildren',
      align: 'center',
      customRender: ({ text }) => (text == true ? '不支持' : '支持')
    },
    {
      title: '是否可重复预订',
      dataIndex: 'isRepeat',
      key: 'isRepeat',
      align: 'center',
      customRender: ({ text }) => (text == true ? '不可以' : '可以')
    },
    {
      title: '场地状态',
      dataIndex: 'isStatus',
      key: 'isStatus',
      align: 'center',
      customRender: ({ text }) => (text == 0 ? '开启' : '关闭')
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      width: 100,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
      align: 'center',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center'
    }
  ]);

  // 当前编辑数据
  const current = ref<BookingField | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示时段弹窗
  const showPeriodEidt = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    console.log(props);
    console.log(props.categoryId);
    if (props.categoryId) {
      where.sid = props.categoryId;
    }
    // 按条件排序
    if (filters) {
      where.virtualViews = filters.virtualViews;
      where.actualViews = filters.actualViews;
      where.sortNumber = filters.sortNumber;
      where.status = filters.status;
    }
    // where.merchantId = getMerchantId();
    return pageBookingField({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  /* 搜索 */
  const reload = (where?: BookingFieldParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: BookingField) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  const openPeriod = () => {
    showPeriodEidt.value = true;
  };

  /* 删除单个 */
  const remove = (row: BookingField) => {
    const hide = message.loading('请求中..', 0);
    removeBookingField(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchBookingField(selection.value.map((d) => d.id))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: BookingField) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  // 监听场馆场地 id 变化
  watch(
    () => props.categoryId,
    () => {
      reload();
    }
  );
</script>
