<script setup lang="ts">
import { ref, reactive, shallowRef, onMounted } from 'vue';
import type { SystemItemModel, SystemIteQuery } from '@/model/care.model';
import type { SatisfactionModel } from '@/model/satisfaction.model';
import SetQuestionnaire from '@/satisfaction/SetQuestionnaire.vue';
import SeeSatisfaction from '@/satisfaction/SeeQuestionnaire.vue';
import EditQuestionnaire from '@/satisfaction/EditQuestionnaire.vue';
// 接口数据

import { satisfactionMethod } from '@/request/api/satisfaction.api';
import { usePagination } from 'alova/client';
import dayjs from 'dayjs';

import { type VxeFormListeners, type VxeFormProps, type VxeGridInstance, type VxeGridListeners, type VxeGridProps, VxeUI } from 'vxe-pc-ui';

const model = shallowRef<SystemIteQuery>();
const searchFormProps = reactive<VxeFormProps<SystemIteQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: { name: '', status: '' },
  items: [
    {
      field: 'name',
      title: '问卷名称',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入满意度问卷名称' } },
    },
    {
      field: 'status',
      title: '状态',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择状态',
          options: [
            { label: '启用', value: '0' },
            { label: '停用', value: '1' },
          ],
        },
      },
    },
    {
      span: 6,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '重置', status: 'warning' },
          { name: 'add', content: '新增', status: 'primary' },
        ],
        events: {
          click(slotParams: any, { name }: any) {
            if (name === 'add') {
              // 新增
              editQuestionnaire();
            }
          },
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<SystemIteQuery> = {
  //查询
  submit({ data }) {
    onSearch(data);
  },

  // 重置
  reset({ data }) {
    onSearch(data);
  },
};
function onSearch(data: SystemIteQuery) {
  const status: string = (data as any).status ?? '';
  model.value = { ...data, status: status as any };
  nextTick(() => {
    (searchFormProps.data as any)!.status = status;
  });
}
const gridRef = ref<VxeGridInstance<SystemItemModel>>();
const gridOptions = reactive<VxeGridProps<SystemItemModel>>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: true,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      // buttons: 'handle',
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'name', title: '问卷' },
    { field: 'pushType', title: '通知渠道', slots: { default: 'pushTypeCell' } },
    { field: 'triggerStr', title: '触发条件' },
    { field: 'createTime', title: '创建时间' },
    { field: 'sendCount', title: '已发条数' },
    { field: 'status', title: '启用状态', slots: { default: 'statusCell' } },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 180,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '查看', status: 'primary', name: 'seeDetail' },
          { content: '设置', status: 'primary', name: 'setQuestionnaire' },
        ],
        events: {
          click({ row, rowIndex }: any, { name }: any) {
            let method;
            if (name === 'seeDetail') {
              method = seeDetail;
            } else if (name === 'setQuestionnaire') {
              method = setQuestionnaire;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const {
  loading,
  page,
  pageSize,
  total,
  onSuccess,
  replace,
  refresh,
  remove,
  send: sendRefresh,
} = usePagination((page, size) => satisfactionMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: true,
});
onSuccess((res: any) => {
  gridRef.value?.loadData(res?.data?.data ?? []);
});
onMounted(() => {
  onSearch(toRaw(searchFormProps.data) as any);
});

// 新增满意度问卷
function editQuestionnaire() {
  VxeUI.modal.open({
    title: '新增满意度问卷',
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `edit-questionnaire-modal`,
    slots: {
      default() {
        return h(EditQuestionnaire, <any>{
          data: {},
          onSubmit(data: Partial<SatisfactionModel['satisfiesyContent']>) {
            refresh(page.value);
            VxeUI.modal.close(`edit-questionnaire-modal`);
          },
          back() {
            VxeUI.modal.close(`edit-questionnaire-modal`);
          },
        });
      },
    },
  });
}
// 设置满意度问卷
function setQuestionnaire(model?: SystemItemModel, index?: number) {
  VxeUI.modal.open({
    title: model?.name ?? '满意度问卷',
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `set-satisfaction-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(SetQuestionnaire, <any>{
          data: model,
          onSubmit(data: SatisfactionModel) {
            refresh(page.value);
            VxeUI.modal.close(`set-satisfaction-modal`);
          },
        });
      },
    },
  });
}

function seeDetail(model?: SystemItemModel, index?: number) {
  VxeUI.modal.open({
    title: model?.name,
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `see-satisfaction-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(SeeSatisfaction, <any>{
          data: model,
        });
      },
    },
  });
}
// 日期验证
const updateTimeStart = ref<string>('');
const updateTimeEnd = ref<string>('');
// 禁用结束时间的日期（早于开始时间的日期）
function disabledEndDate(current: any) {
  if (!updateTimeStart.value) return false;
  return current && current < dayjs(updateTimeStart.value);
}
defineExpose({
  send: sendRefresh,
});
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits">
        <template #createTimes>
          <div class="date-range-container">
            <a-date-picker v-model:value="updateTimeStart" placeholder="请选择开始时间" style="flex: 1" :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="updateTimeEnd" placeholder="请选择结束时间" style="flex: 1" :disabledDate="disabledEndDate" :show-time="{ format: 'HH:mm' }" />
          </div>
        </template>
      </vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #statusCell="{ row }">
          {{ row.status == '0' ? '启用' : '停用' }}
        </template>
        <template #pushTypeCell="{ row }">
          {{ row.pushType == '0' ? '站内' : '-' }}
        </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 {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.date-range-container {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .vxe-input {
    flex: 1;
    min-width: 0;
  }

  .date-separator {
    color: #666;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
    padding: 0 8px;
  }
}
</style>
