<script setup lang="ts">
import { h } from 'vue';
import { conditioningStatus, orderStatus } from '@/model/options';
import { getConditioningRecordMethod } from '@/request/api/care.api';
import type { ConditioningRecordListModel, ConditioningRecordListQuery } from '@/model/care.model';

import OrderDetail from '@/service/OrderDetail.vue';
import CareProcess from '@/service/CareProgress.vue';
import { usePagination } from 'alova/client';
import dayjs from 'dayjs';

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

defineOptions({
  name: 'OrderManagement',
});

const model = shallowRef<ConditioningRecordListQuery>();

const orderTimeStart = ref<string>('');
const orderTimeEnd = ref<string>('');
const payTimeStart = ref<string>('');
const payTimeEnd = ref<string>('');

// 禁用结束时间的日期
function disabledOrderEndDate(current: any) {
  if (!orderTimeStart.value) return false;
  return current && current < dayjs(orderTimeStart.value);
}

function disabledPayEndDate(current: any) {
  if (!payTimeStart.value) return false;
  return current && current < dayjs(payTimeStart.value);
}

const searchFormProps = reactive<VxeFormProps<ConditioningRecordListQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'conditioningWrapName',
      title: '服务包名称',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'patientName',
      title: '姓名',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'progress',
      title: '调理状态',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        options: conditioningStatus,
        props: { placeholder: '请选择', clearable: true },
      },
    },
    {
      field: 'orderStatus',
      title: '订单状态',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        options: orderStatus,
        props: { placeholder: '请选择', clearable: true },
      },
    },
    {
      field: 'orderTime',
      title: '下单时间',
      span: 10,
      slots: {
        default: 'orderTimeRange',
      },
    },
    {
      field: 'payTime',
      title: '付款时间',
      span: 10,
      slots: {
        default: 'payTimeRange',
      },
    },
    {
      span: 6,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空' },
        ],
        events: {
          click() { },
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<ConditioningRecordListQuery> = {
  submit({ data }) {
    model.value = {
      ...data,
      orderTimeStart: orderTimeStart.value ? dayjs(orderTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      orderTimeEnd: orderTimeEnd.value ? dayjs(orderTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
      payTimeStart: payTimeStart.value ? dayjs(payTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      payTimeEnd: payTimeEnd.value ? dayjs(payTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
    } as any;
  },
  // 重置
  reset({ data }) {
    model.value = { ...data } as any;
    orderTimeStart.value = '';
    orderTimeEnd.value = '';
    payTimeStart.value = '';
    payTimeEnd.value = '';
  },
};
const gridRef = ref<VxeGridInstance<ConditioningRecordListModel>>();
const gridOptions = reactive<VxeGridProps<ConditioningRecordListModel>>({
  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: 'orderNo', title: '订单编号' },
    { field: 'createTime', title: '创建时间' },
    { field: 'payTime', title: '付款时间' },
    { field: 'patientName', title: '姓名' },
    { field: 'conditioningWrapName', title: '服务包名称' },
    { field: 'diagnosis', title: '疾病名称' },
    { field: 'symptom', title: '证型' },
    { field: 'constitutionGroupName', title: '体质' },
    { field: 'createBy', title: '开具医生' },
    { field: 'estimatedStartDate', title: '开始调养日期' },
    { field: 'progress', title: '调理状态', slots: { default: 'patients' } },
    { field: 'orderStatus', title: '订单状态', slots: { default: 'orderStatus' } },
    { field: 'cost', title: '订单金额' },
    { field: 'profitSharing', title: '分账' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 200,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '详情', status: 'primary', name: 'serviceDetail' },
          { content: '调养过程', status: 'primary', name: 'conditioningProcess' },
        ],
        events: {
          click({ row }: { row: ConditioningRecordListModel }, { name }: { name: string }) {
            if (name === 'serviceDetail') {
              serviceDetail(row);
            } else if (name === 'conditioningProcess') {
              conditioningProcess(row);
            }
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

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

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

function conditioningProcess(model?: ConditioningRecordListModel) {
  VxeUI.modal.open({
    title: model?.id ? `调养过程` : `新增调养过程`,
    height: window.innerHeight,
    width: window.innerWidth,
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    id: `conditioning-process-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(CareProcess, {
          data: model,
          onSubmit() {
            refresh(page.value);
            VxeUI.modal.close(`conditioning-process-modal`);
          },
        } as any);
      },
    },
  });
}
// 点击详情
function serviceDetail(model?: ConditioningRecordListModel) {
  const types = 'record';
  VxeUI.modal.open({
    id: 'servicePackageDetail-modal',
    title: '调养记录详情',
    height: window.innerHeight,
    width: window.innerWidth,
    fullscreen: true,
    escClosable: true,
    destroyOnClose: true,
    slots: {
      default() {
        return h(OrderDetail, {
          data: {
            ...model,
            types,
          },
          onVoidSubmit() {
            refresh(page.value);
          },
        } as any);
      },
    },
  });
}
const progressTextMap: Record<string, string> = {
  '3': '未开始',
  '4': '调理中',
  '5': '已完结',
};

const orderStatusTextMap: Record<string, string> = {
  '1': '交易关闭（已作废）',
  '0': '待付款',
  '2': '交易关闭（用户取消）',
  '6': '已付款',
  '345': '交易成功',
};


</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits">
        <template #orderTimeRange>
          <div class="date-range-container">
            <a-date-picker v-model:value="orderTimeStart" placeholder="请选择开始时间" style="flex: 1"
              :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="orderTimeEnd" placeholder="请选择结束时间" style="flex: 1"
              :disabledDate="disabledOrderEndDate" :show-time="{ format: 'HH:mm' }" />
          </div>
        </template>
        <template #payTimeRange>
          <div class="date-range-container">
            <a-date-picker v-model:value="payTimeStart" placeholder="请选择开始时间" style="flex: 1"
              :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="payTimeEnd" placeholder="请选择结束时间" style="flex: 1"
              :disabledDate="disabledPayEndDate" :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 #cell="{ row }">{{ row.progress === 1 ? '已开始' : row.progress === 2 ? '已结束' : '未开始' }} </template>
        <template #patients="{ row }">
          <div>
            {{ progressTextMap[row.progress] || '' }}
          </div>
        </template>
        <template #orderStatus="{ row }">
          <div>
            {{ orderStatusTextMap[row.orderStatus] || '' }}
          </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);
}

.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>
