<template>
  <div class="container">
    <Breadcrumb :items="['消息管理', '公告设置']" />
    <a-card class="general-card" title=" ">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="right"
          >
            <a-row :gutter="18">
              <a-col :span="9">
                <a-form-item
                  field="title"
                  label='标题'
                >
                  <a-input
                    v-model="formModel.title"
                    style="width: 360px"
                    placeholder='请输入标题'
                  />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item field="Time" label='时间'>
                  <a-range-picker
                    show-time
                    format="YYYY-MM-DD HH:mm"
                    @ok="timeRangs"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item
                  field="enable"
                  label='状态'
                >
                  <a-select
                    v-model="formModel.state"
                    style="width: 360px"
                    placeholder='请选择状态'
                    :options="statusOptions"
                  />
                </a-form-item>
              </a-col>



            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <a-divider style="margin-top: 0" />
      <a-row>
        <a-col :span="12">
          <a-space>
            <BulletinEdit ref="createUserRef" :is-create="true" @refresh="search" />
            <a-button type="primary" @click="publishBulletin(selectedIds)">
              <template #icon><icon-public /></template>
              发布
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="
            display: flex;
            align-items: center;
            justify-content: end;
            padding-bottom: 20px;
          "
        >
          <a-tooltip content='刷新'>
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>

          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content='密度'>
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>

          <a-tooltip content='列设置'>
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>

      <a-table
        row-key="id"
        :loading="loading"
        :pagination="false"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        style="margin-bottom: 40px"
        @page-change="onPageChange"
      >
        <template #id="{ record }">
          <a-checkbox v-model="selectedIds" :value="record.id" style="margin-left: -5px"> </a-checkbox>
        </template>
        <template #publishTime="{ record }">
          {{ dayjs(record.publishTime).format('YYYY-MM-DD HH:mm') }}
        </template>
        <template #state="{ record }">
          <span v-if="record.state === 'publish'">已发布</span>
          <span v-else-if="record.state === 'edit'">编辑中</span>
          <span v-else-if="record.state === 'close'">已关闭</span>
<!--          <a-switch-->
<!--            :model-value="record.state"-->
<!--            :checked-value="record.state ? 'publish' || 'edit' : 'close' "-->
<!--            :unchecked-value="record.state ? 'close' : 'publish' || 'edit' "-->
<!--            @change="handleClose(record.id)"-->
<!--          />-->
        </template>
        <template #top="{ record }">
          <a-switch
            :model-value="record.top"
            :checked-value="true"
            :unchecked-value="false"
            @change="handleSwitchChange(record)"
          />
        </template>
        <template #operations="{ record }">
          <a-button
          type="outline"
          size="small"
          status="success"
          style="padding: 7px; margin-right: 10px"
          @click="openDetail(record.id)"
        >
          <template #icon><icon-list /></template>
          详情
        </a-button>
          <BulletinEdit
            ref="editUserRef"
            :prem="record"
            :is-create="false"
            @refresh="fetchData"
          />
          <a-popconfirm
            content='确认删除此公告？'
            type="error"
            @ok="handleDelete(record.id)"
          >
            <a-button
              v-permission="['message:bulletin:delete']"
              type="outline"
              size="small"
              status="danger"
              style="padding: 7px;margin-right: 10px"
            >
              <template #icon><icon-delete /></template>
              删除
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            :content="record.state === 'publish'? '确认关闭此公告？' : '确认编辑此公告?'"
            type="error"
            @ok="handleClose(record.id)"
          >
            <a-button
              type="outline"
              size="small"
              status="warning"
              style="padding: 7px;margin-right: 10px"
            >
              <template #icon><icon-poweroff /></template>
              切换状态
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
      <a-pagination
        style="float: right; position: relative; right: 1px; bottom: 25px"
        :total="pagination.total"
        :size="size"
        show-total
        show-jumper
        show-page-size
        @page-size-change="onSizeChange"
        @change="onPageChange"
      />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted, ref, watch } from 'vue';
  import useLoading from '@/hooks/loading';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { useBulletinStore } from '@/store';
  import useTableOption from '@/hooks/table-option';
  import usePagination from '@/hooks/pagination';
  import dayjs from 'dayjs';
  import { BulletinRecord, BulletinsRecord } from '@/api/bulletin-mgmt';
  import { Message } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  import BulletinEdit from './components/bulletin-edit.vue';

  const generateFormModel = () => {
    return {
      title: '',
      state: '',
      publishTimeBegin: '',
      publishTimeEnd: '',
    };
  };

  const { pagination,setPagination } = usePagination();
  const { loading, setLoading } = useLoading(true);
  const renderData = ref<BulletinRecord[]>([]);
  const formModel = ref(generateFormModel());
  const router = useRouter();
  const selectedIds= ref<number[]>([]);
  const {
    cloneColumns,
    showColumns,
    densityList,
    size,
    handleSelectDensity,
    handleChange,
    popupVisibleChange,
    deepClone,
  } = useTableOption();

  const bulletinStore = useBulletinStore();

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '#',
      dataIndex: 'id',
      slotName: 'id',
      width: 60,
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '时间',
      dataIndex: 'publishTimeBegin',
      slotName: 'publishTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      slotName: 'state',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '置顶',
      dataIndex: 'top',
      slotName:'top',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '操作',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: '已发布',
      value: 'publish',
    },
    {
      label: '编辑中',
      value: 'edit',
    },
    {
      label: '已关闭',
      value: 'close',
    },
  ]);

  // 获取公告列表
  const fetchData = async (
    params = { size: 10, current: 1 }
  ) => {
    setLoading(true);
    try {
      const res: any = await bulletinStore.queryBulletinList(params);
      renderData.value = res.data.records;
      setPagination(res.data);
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  // 查询
  const search = () => {
    fetchData({
      ...pagination,
      ...formModel.value,
    } as unknown as BulletinsRecord);
    selectedIds.value = [];
  };

  // 分页发生改变
  const onPageChange = (current: number) => {
    pagination.page = current;
    pagination.current = current;
    search();
  };
  // 时间范围
  const timeRangs = (dateString: string[]) => {
    // eslint-disable-next-line prefer-destructuring
    formModel.value.publishTimeBegin = dateString[0];
    // eslint-disable-next-line prefer-destructuring
    formModel.value.publishTimeEnd = dateString[1];
  };

  // 数据条数改变
  const onSizeChange = (Size: number) => {
    pagination.size = Size;
    search();
  };


  // 重置
  const reset = () => {
    formModel.value = generateFormModel();
  };

  // 是否置顶
  const handleSwitchChange = async (record: any) => {
    record.top = !record.top;
    const res = await bulletinStore.toggleBulletin(record.id);
    if (res.status === 200) {
      Message.success({
        content: '修改置顶成功',
        duration: 3 * 1000,
      });
    } else {
      Message.error({
        content: '修改置顶失败',
        duration: 3 * 1000,
      });
    }
  };

  // 打开详情
  function openDetail(id:number): void{
    const url = router.resolve({
      name: 'BulletinDetail',
      params: {id}
    }).href;
    router.push(url);
  };

  // 发布公告
  const publishBulletin = async (data:number[]) => {
    const res = await bulletinStore.publishBulletin(data);
    if (res.status === 200) {
      Message.success({
        content: '发布成功',
        duration: 5 * 1000,
      });
    }
    search();
  };

  // 关闭公告
  const handleClose = async (id: number) => {
    const res = await bulletinStore.closeBulletin(id);
    if (res.status === 200) {
      Message.success({
        content: '切换成功',
        duration: 5 * 1000,
      });
    }
    search();
  };

  // 删除
  const handleDelete = async (id: number) => {
    const res = await bulletinStore.removeBulletin(id);
    if (res.status === 200) {
      Message.success({
        content: '删除成功',
        duration: 5 * 1000,
      });
      search();
    }
  };
  onMounted(() => {
    search();
  });
  watch(() => columns.value, deepClone, { deep: true, immediate: true });
</script>

<script lang="ts" >
  export default {
    name: 'Bulletin',
  };
</script>



<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>