<script setup lang="ts">
import { ref, reactive, shallowRef, onMounted, toRaw, computed } from 'vue';
import { profitSharingStatus } from '@/model/options';
import dayjs from 'dayjs';
import type { RevenueSharingDetailModel, RevenueSharingDetailQuery } from '@/model/order.model';
import type { ConditioningRecordListModel } from '@/model/care.model';
import OrderDetail from '@/service/OrderDetail.vue';
import { getAllSupplierMethod } from '@/request/api/care.api';
// 接口数据
import {
    getRevenueSharingDetailListMethod,
  } from '@/request/api/order.api';
import { usePagination } from 'alova/client';

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




const model = shallowRef<RevenueSharingDetailQuery>();
const searchFormProps = reactive<VxeFormProps<RevenueSharingDetailQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'orderNo',
      title: '订单编号',
      span: 4,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'profitSharingStatus',
      title: '分账状态',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        options: profitSharingStatus,
        props: { placeholder: '状态' },
      },
    },
    {
      field: 'conditioningProgramSupplierName',
      title: '供应商',
      span: 4,
      itemRender: {
        name: 'VxeSelect',
        optionProps: {
          value: 'value', // 供应商id
          label: 'label', // 供应商名称
        },
        props: { placeholder: '请选择', options: computed(() => supplierOptions.value as any[]), clearable: true },
      },
    },
    {
      field: 'profitSharingTime',
      title: '分账时间',
      span: 10,
      slots: {
        default: 'revenueTimeRange',
      },
    },
    {
      span: 8,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '重置' },
        ],
        events: {
            click() {},
        },
      },
    },
  ],
});
const profitSharingTimeStart = ref<string>('');
const profitSharingTimeEnd = ref<string>('');
function disabledRevenueEndDate(current: any) {
  if (!profitSharingTimeStart.value) return false;
  return current && current < dayjs(profitSharingTimeStart.value);
}
const searchFormEmits: VxeFormListeners<RevenueSharingDetailQuery> = {
  submit({ data }) {
    let supplierName = '';
    if (data.conditioningProgramSupplierName) {
      const supplier = supplierArr.value.find((item: any) => item.id === data.conditioningProgramSupplierName);
      supplierName = supplier?.name || '';
    }
    
    model.value = {
      ...data,
      conditioningProgramSupplierName: supplierName, 
      profitSharingTimeStart: profitSharingTimeStart.value ? dayjs(profitSharingTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      profitSharingTimeEnd: profitSharingTimeEnd.value ? dayjs(profitSharingTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
    };
  },
  // 重置
  reset({ data }) {
    model.value = { ...data };
    profitSharingTimeStart.value = '';
    profitSharingTimeEnd.value = '';
  },
};
const gridRef = ref<VxeGridInstance<RevenueSharingDetailModel>>();
const gridOptions = reactive<VxeGridProps<RevenueSharingDetailModel>>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  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: 'orderNo', title: '订单编号', slots: { default: 'orderNoCell' }  },
    { field: 'payTime', title: '付款时间' },
    { field: 'finishTime', title: '收货/核销/完成时间' },
    { field: 'profitSharingTime', title: '分账时间' },
    { field: 'conditioningProgramName', title: '项目名称' },
    { field: 'totalMeasure', title: '数量' },
    { field: 'pricingUnit', title: '单位' },
    { field: 'unitPrice', title: '单价（元）' },
    { field: 'totalPrice', title: '总价（元）' },
    { field: 'conditioningProgramSupplierName', title: '供应商' },
    { field: 'profitSharingStatus', title: '分账状态', slots: { default: 'revenueStatusCell' } },
    { field: 'profitSharing', title: '分账比例' },
    { field: 'profitSharingAmount', title: '预计分账金额' },
    { field: 'realAmount', title: '到账金额' },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

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

const supplierOptions = ref<{ label: string; value: string }[]>([]);
const supplierArr = ref<any[]>([]);
async function getSupplier(params: any) {
  supplierOptions.value = [];
  const res = (await getAllSupplierMethod(params)) as any[];
  if (Array.isArray(res) && res.length > 0) {
    supplierArr.value = res;
    supplierOptions.value = res.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  }
}

onMounted(() => {
  model.value = toRaw(searchFormProps.data);
  getSupplier({});
});
// 点击项目名称查看商品详情
function serviceDetail(model?: ConditioningRecordListModel) {
  const types = 'record';
  console.log('model===', model);
  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);
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits">
        <template #revenueTimeRange>
          <div class="date-range-container">
            <a-date-picker v-model:value="profitSharingTimeStart" placeholder="请选择开始时间" style="flex: 1"
              :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="profitSharingTimeEnd" placeholder="请选择结束时间" style="flex: 1"
              :disabledDate="disabledRevenueEndDate" :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 #orderNoCell="{ row }">
          <span class="order-no-link" @click="serviceDetail(row as any)">{{ row.orderNo }}</span>
        </template>
        <template #revenueStatusCell="{ row }">
          <span>{{ row.profitSharingStatus === '1' ? '未分账' : row.revenueStatus === '2' ? '已分账' : row.profitSharingStatus === '3' ? '分账异常' : '' }}</span>
        </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-separator {
  margin: 0 10px;
}

.order-no-link {
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
    color: #40a9ff;
  }
}
</style>
