<script setup lang="ts">
import { h } from 'vue';
import EditEducation from '@/components/EditEducation.vue';
import type { EducationModel, EducationQuery } from '@/model/education.model';
import { usePagination } from 'alova/client';
import { notification } from 'ant-design-vue';
// 接口数据
import { deleteEducationMethod, educationMethod, updateEducationStatusMethod } from '@/request/api/education.api';
import { type VxeFormListeners, type VxeFormProps, type VxeGridInstance, type VxeGridListeners, type VxeGridProps, VxeUI } from 'vxe-pc-ui';

const model = shallowRef<EducationQuery>();
const searchFormProps = reactive<VxeFormProps<EducationQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'title',
      title: '标题',
      span: 4,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'createBy',
      title: '创建者',
      span: 4,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'status',
      title: '状态',
      span: 4,
      itemRender: {
        name: 'VxeRadioGroup',
        options: [
          { label: '启用', value: '0' },
          { label: '禁用', value: '1' },
        ],
      },
    },
    {
      span: 7,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空' },
          { name: 'add', content: '新增', status: 'primary' },
        ],
        events: {
          click(slotParams, { name }) {
            if (name === 'add') {
              // 新增
              editEducation();
            }
          },
        },
      },
    },
  ],
});

const searchFormEmits: VxeFormListeners<EducationQuery> = {
  // 查询
  submit({ data }) {
    model.value = { ...data };
  },
  // 重置
  reset({ data }) {
    model.value = { ...data };
  },
};
const gridRef = ref<VxeGridInstance<EducationModel>>();
const gridOptions = reactive<VxeGridProps<EducationModel>>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'title', title: '标题' },
    { field: 'tagNames', title: '用户标签' },
    { field: 'createBy', title: '创建者' },
    { field: 'createTime', title: '创建时间' },
    {
      field: 'status',
      title: '启用状态',
      align: 'center',
      cellRender: {
        name: 'VxeSwitch',
        props: {
          openLabel: '启用',
          openValue: '0',
          closeLabel: '禁用',
          closeValue: '1',
        },
        events: {
          change({ row, rowIndex }, { value }) {
            row.status = { '1': '0', '0': '1' }[value as string] as any;
            updatePlanStatus(row, rowIndex, value);
          },
        },
      },
    },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 180,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '编辑', status: 'primary', name: 'editEducation' },
          { content: '删除', status: 'primary', name: 'deleteEducation' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'editEducation') {
              method = editEducation;
            } else if (name === 'deleteEducation') {
              method = deleteEducation;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination((page, size) => educationMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: false,
});
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});

onMounted(async () => {
  model.value = toRaw(searchFormProps.data);
});

function updatePlanStatus(model: EducationModel, index: number, status: EducationModel['status']) {
  const { id, title } = model;
  const label = { '1': '禁用', '0': '启用' }[status];
  VxeUI.modal.confirm({
    title: `启用状态`,
    content: `确认要 ${label} ${title} 吗？`,
    showClose: false,
    onConfirm() {
      updateEducationStatusMethod({ id, status }).then(() => {
        notification.success({
          message: `${label}: ${title}`,
          description: '操作成功',
        });
        model.status = status;
        replace(model, index);
      });
    },
  });
}

function deleteEducation(model: EducationModel, index: number) {
  const { title } = model;
  VxeUI.modal.confirm({
    title: `删除宣教`,
    content: `确认要删除 ${title} 吗？`,
    showClose: false,
    onConfirm() {
      deleteEducationMethod(model).then(() => {
        notification.success({
          message: `删除宣教: ${title}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}

function editEducation(model?: EducationModel, index?: number) {
  VxeUI.modal.open({
    title: model?.id ? `修改宣教` : `新增宣教`,
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `education-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditEducation, <any>{
          data: model,
          onSubmit: (data: EducationModel) => {
            refresh(page.value);
            VxeUI.modal.close(`education-modal`);
          },
        });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits"></vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #cell="{ row }">{{ row.progress === '1' ? '进行中' : row.progress === '2' ? '已结束' : row.progress === '0' ? '未开始' : '' }} </template>
        <template #patients="{ row }">
          <div :class="row.isFilter === 'Y' ? '' : 'text-red'">
            {{ row.isFilter === 'Y' ? '已筛选' : '未筛选' }}
          </div>
        </template>
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>
      </vxe-grid>
    </main>
    <footer class="flex-none">
      <vxe-pager
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
      />
    </footer>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  padding: 0 24px;
  max-height: var(--page-main-container);
}
</style>
