<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="$t('标题')"
                >
                  <a-input
                    v-model="formModel.title"
                    style="width: 360px"
                    :placeholder="$t('请输入标题')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item
                  field="enable"
                  :label="$t('状态')"
                >
                  <a-select
                    v-model="formModel.states"
                    style="width: 360px"
                    :placeholder="$t('请选择状态')"
                    :options="statusOptions"
                  />
                </a-form-item>
              </a-col>

              <a-col :span="9">
                <a-form-item field="publishTimeBegin" :label="$t('开始时间')">
                  <a-date-picker
                    v-model="formModel.publishTimeBegin"
                    style="width: 360px"
                    show-time
                    :time-picker-props="{ defaultValue: '09:09:06' }"
                    format="YYYY-MM-DD HH:mm"
                    :allow-clear="false"
                    @select="onSelect"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="publishTimeEnd" :label="$t('结束时间')">
                  <a-date-picker
                    v-model="formModel.publishTimeEnd"
                    style="width: 360px"
                    show-time
                    :time-picker-props="{ defaultValue: '09:09:06' }"
                    format="YYYY-MM-DD HH:mm"
                    :allow-clear="false"
                    @select="onSelect"
                  />
                </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>
            <NoticeEdit ref="createUserRef" :is-create="true" @refresh="search" />
          </a-space>
          <a-button style="margin-left: 20px" @click="generateExcel">
            <template #icon>
              <icon-download size="18" />
            </template>
            导出
          </a-button>
        </a-col>
        <a-col
          :span="12"
          style="
            display: flex;
            align-items: center;
            justify-content: end;
            padding-bottom: 20px;
          "
        >
          <a-tooltip :content="$t('刷新')">
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>

          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('密度')">
              <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 === sizeof }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>

          <a-tooltip :content="$t('列设置')">
            <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"
        :filter-icon-align-left="alignLeft"
        @change="handleSortChange"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.size }}
        </template>
        <template #enabled="{ record }">
          <a-switch
            :model-value="record.enabled"
            :checked-value="true"
            :unchecked-value="false"
            @change="enabledStatus(record)"
          />
        </template>
        <template #operations="{ record }">
          <a-button
            type="outline"
            size="small"
            status="success"
            style="padding: 7px;margin-right: 10px"
          >
            <template #icon><icon-list /></template>
            详情
          </a-button>

          <NoticeEdit
            ref="editUserRef"
            :prem="record"
            :is-create="false"
            @refresh="fetchData"
          />
          <a-button
            type="outline"
            size="small"
            status="danger"
            style="padding: 7px"
          >
            <template #icon><icon-delete /></template>
            删除
          </a-button>

        </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, ref, watch } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { UserRecord, UserParams } from '@/api/user';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { useUserStore } from '@/store';
  import { Message } from '@arco-design/web-vue';
  import useTableOption from '@/hooks/table-option';
  import NoticeEdit from './components/notice-edit.vue';

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

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<UserRecord[]>([]);
  const formModel = ref(generateFormModel());

  const {
    cloneColumns,
    showColumns,
    densityList,
    handleSelectDensity,
    handleChange,
    popupVisibleChange,
    deepClone,
  } = useTableOption();
  const sizeof=useTableOption().size;

  const userStore = useUserStore();

  const pagination: Pagination = {
    page: 1,
    size: 10,
    current: 1,
    total: null,
  };

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      width: 60,
    },
    {
      title: '标题',
      dataIndex: 'title',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: t('时间'),
      dataIndex: 'publishTimeBegin',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: t('状态'),
      dataIndex: 'states',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '操作',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('已发布'),
      value: 'true',
    },
    {
      label: t('未发布'),
      value: 'false',
    },
  ]);

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

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

  // 分页发生改变
  const onPageChange = (current: number) => {
    pagination.page = current;
    pagination.current = current;
    search();
  };

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

  search();

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

  // 表格内部排序
  const alignLeft = ref(false);
  const handleSortChange = (data: any, extra: any, currentDataSource: any) => {};

  // 是否启用
  const enabledStatus = async (record: string) => {
    record.enabled = !record.enabled;
    const res = await userStore.enabledUser(record.id);
    if (res.status === 200) {
      Message.success({
        content: t('modify.status.sucess'),
        duration: 3 * 1000,
      });
    } else {
      Message.error({
        content: t('modify.status.fail'),
        duration: 3 * 1000,
      });
    }
  };

  // 删除
  // const handleDelete = async (record: UserRecord) => {
  //   const res = await userStore.removeUser(record.id);
  //   if (res.status === 200) {
  //     Message.success({
  //       content: '删除成功',
  //       duration: 5 * 1000,
  //     });
  //     search();
  //   }
  // };

  watch(() => columns.value, deepClone, { deep: true, immediate: true });
</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>