 <template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="language" @change="changeTable">
        <a-tab-pane key="cn" tab="Chinese" />
        <a-tab-pane key="en" tab="English" />
      </a-tabs>
    </template>

    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="openModal(true, {language})" v-if="getCheckPerm('news-add')">
            新增新闻</a-button
          >
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '撤回',
                //icon: 'icon-park-outline:folder-withdrawal-one',
                ifShow: getCheckPerm('news-withdraw') && record.isPublic == 1,
                onClick: handleWithdraw.bind(null, record),
              },
              {
                label: '发布',
                //icon: 'arcticons:efa-publish',
                ifShow: getCheckPerm('news-publish') && record.isPublic == 0,
                onClick: handlePublish.bind(null, record),
              },
              {
                label: '编辑',
                //icon: 'ep:edit',
                ifShow: getCheckPerm('news-edit') && record.isPublic == 0,
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                ifShow: getCheckPerm('news-delete'),
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <addNewModal @register="register" @update="reload" />
  </PageWrapper>
</template>
<script lang="ts">
import { defineComponent, h, ref } from 'vue';
import {
  BasicTable,
  useTable,
  TableAction,
  BasicColumn,
  TableImg,
  FormProps,
} from '/@/components/Table';
import { PageWrapper } from '/@/components/Page';
import { Time } from '/@/components/Time';
import { ListApi, NewDisplay, NewPutTop, NewPublicNews, newDelete } from '/@/api/operate';
import {  Descriptions, Switch, Tabs } from 'ant-design-vue';
import { useModal } from '/@/components/Modal';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import addNewModal from './components/new/addModal.vue';
import { usePermissionStore } from '/@/store/modules/permission';
export default defineComponent({
  components: {
    BasicTable,
    TableAction,
    PageWrapper,
    TableImg,
    addNewModal,
    [Descriptions.name]: Descriptions,
    [Descriptions.Item.name]: Descriptions.Item,
    [Tabs.name]: Tabs,
    [Tabs.TabPane.name]: Tabs.TabPane,
  },
  setup() {
    const { t } = useI18n();
    const { createMessage } = useMessage();
    const permissionStore = usePermissionStore();
    const { getCheckPerm } = permissionStore;
    const [register, { openModal }] = useModal();
    const language = ref<string>('cn'); //未处理，0已处理（默认1）
    const columns: BasicColumn[] = [
      {
        title: '新闻标题',
        dataIndex: 'title',
        ellipsis: true,
        width: 250,
      },
      {
        title: '来源',
        dataIndex: 'source',
        ellipsis: true,
        width: 120,
      },
      {
        title: '类型',
        dataIndex: 'newType',
        ellipsis: true,
        width: 80,
        customRender: ({ record }) => {
          return record.newType == 1 ? '链接' : '图文';
        },
      },
      {
        title: '创建人',
        ellipsis: true,
        dataIndex: 'creater',
        width: 80,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 150,
        customRender: ({ record }) => {
          return (
            record.createTime &&
            h(Time, {
              value: record.createTime,
              mode: 'datetime',
            })
          );
        },
      },
      {
        title: '发布时间',
        dataIndex: 'publicTime',
        width: 150,
        customRender: ({ record }) => {
          return (
            record.publicTime &&
            h(Time, {
              value: record.publicTime,
              mode: 'datetime',
            })
          );
        },
      },
      {
        title: '是否显示',
        dataIndex: 'display',
        ifShow: getCheckPerm('news-display'),
        width: 80,
        customRender: ({ record }) => {
          if (!Reflect.has(record, 'pendingStatus')) {
            record.pendingStatus = false;
          }
          return h(Switch, {
            checked: record.display === 1,
            checkedChildren: '是',
            unCheckedChildren: '否',
            loading: false,
            onChange: async (checked: boolean) => {
              record.pendingStatus = true;
              const id: string = record.id || '';
              const newStatus = checked ? 1 : 0;
              Reflect.set(record, 'display', newStatus);
              await NewDisplay({ id: id, display: newStatus });
              createMessage.success(t('common.optSuccess'));
              // reload()
            },
          });
        },
      },
      {
        title: '置顶',
        dataIndex: 'isTop',
        ifShow: getCheckPerm('news-top'),
        width: 80,
        customRender: ({ record }) => {
          if (!Reflect.has(record, 'pendingStatus')) {
            record.pendingStatus = false;
          }
          return h(Switch, {
            checked: record.isTop === 1,
            checkedChildren: '是',
            unCheckedChildren: '否',
            loading: false,
            onChange: async (checked: boolean) => {
              record.pendingStatus = true;
              const id: string = record.id || '';
              const newStatus = checked ? 1 : 0;
              // Reflect.set(record, 'isOnSale', newStatus);
              await NewPutTop({ id, isTop: newStatus });
              createMessage.success(t('common.optSuccess'));
              reload();
            },
          });
        },
      },
    ];
    const searchForm: Partial<FormProps> = {
      labelWidth: 100,
      autoSubmitOnEnter: true,
      schemas: [
        {
          field: 'ctivated',
          label: t('routes.operate.releaseTime'),
          component: 'RangePicker',
          componentProps: {
            maxLength: 100,
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            showTime: true,
          },
          colProps: {
            xl: 11,
            xxl: 11,
          },
        },
        {
          field: 'title',
          label: t('routes.operate.newsTitle'),
          component: 'Input',
          colProps: {
            xl: 6,
            xxl: 6,
          },
        },
      ],
    };
    const [registerTable, { reload }] = useTable({
      api: ListApi,
      title: '新闻列表',
      columns: columns,
      useSearchForm: true,
      formConfig: searchForm,
      showTableSetting: true,
      showIndexColumn: false,
      searchInfo: { language },
      rowKey: 'id',
      fetchSetting: {
        pageField: 'pageNum',
        sizeField: 'pageSize',
        listField: 'list',
        totalField: 'total',
      },
      beforeFetch: (T) => {
        if (T.ctivated) {
          T.publicTimeStart = T.ctivated[0];
          T.publicTimeEnd = T.ctivated[1];
        }
        return T;
      },
      actionColumn: {
        width: 220,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
      canResize: true,
    });
    async function handleDelete(record: Recordable) {
      await newDelete({ id: record.id });
      createMessage.success(t('common.optSuccess'));
      reload();
    }
    async function handlePublish(record: Recordable) {
      console.log('点击了发布', record);
      await NewPublicNews({ id: record.id, isPublic: 1 });
      createMessage.success(t('common.optSuccess'));
      reload();
    }
    function handleEdit(record: Recordable) {
      console.log('点击了编辑', record);
      openModal(true, {...record,language});
    }
    async function handleWithdraw(record: Recordable) {
      await NewPublicNews({ id: record.id, isPublic: 0 });
      createMessage.success(t('common.optSuccess'));
      reload();
    }
    function changeTable(val: string) {
        language.value = val;
        reload();
      }
    function hendleAddNew() {
      console.log('新增新闻');
    }
    return {
      registerTable,
      handleDelete,
      handleEdit,
      handleWithdraw,
      handlePublish,
      hendleAddNew,
      changeTable,
      reload,
      language,
      register,
      openModal,
      getCheckPerm,
    };
  },
});
</script>