<script setup lang="ts">
import type { SystemItemModel, SystemIteQuery } from '@/model/care.model';
import ServiceDetail from './ServiceDetail.vue';
import AddItems from './AddItems.vue';
import seeHealthEvaluation from './seeHealthEvaluation.vue';
import HealthEvaluation from './HealthEvaluation.vue';
// 接口数据

import { pageConfirmedCpMethod, deleteConfirmedCpMethod } from '@/request/api/care.api';
import { usePagination, useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';

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: { types: ['1'] as any, status: '0' as any },
  items: [
    {
      field: 'institutionName',
      title: '机构名称',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'name',
      title: '项目名称',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'conditioningProgramType',
      title: '方案类型',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      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') {
              // 新增
              editConfirmed();
            }
          },
        },
      },
    },
    { field: 'types', title: '项目应用', span: 6, itemRender: {
        name: 'VxeCheckboxGroup',
        options: [
          { label: '服务包项目', value: '1' },
          { label: '调理方案项目', value: '2' },
        ],
        events: {
          change(value: { data: SystemIteQuery }) { onSearch(value.data) },
        },
      }
    },
    {
      field: 'status',
      title: '启用状态',
      span: 6,
      itemRender: {
        name: 'VxeRadioGroup',
        options: [
          { label: '启用', value: '0' },
          { label: '停用', value: '1' },
        ],
        props: {
          strict: false,
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<SystemIteQuery> = {
  // 查询随访计划
  submit({ data }) {
    onSearch(data);
  },
  
  // 重置
  reset({ data }) {
    onSearch(data);
  },
};
function onSearch(data: SystemIteQuery) {
  const types: string[] = (data as any).types?.length ? (data as any).types : ['1'];
  const status: string = (data as any).status ?? '0';
  const isForWrap: SystemIteQuery['isForWrap'] = types.includes('1') ? 'Y' : null;
  const isForInfer: SystemIteQuery['isForInfer'] = types.includes('2') ? 'Y' : null;

  model.value = { ...data, types: [...types] as any, status: status as any, isForWrap, isForInfer };
  nextTick(() => {
    (searchFormProps.data as any)!.types = [...types];
    (searchFormProps.data as any)!.status = status;
    (searchFormProps.data as any)!.isForInfer = isForInfer;
    (searchFormProps.data as any)!.isForWrap = isForWrap;
  })
}
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: [
    { field: 'name', title: '项目名称' },
    { field: 'conditioningProgramType', title: '方案类型' },
    { field: 'isForWrapCell', title: '项目应用', slots: { default: 'isForWrapCell' } },
    { field: 'cpFixedPricingRule.unitPrice', title: '单价（元）', slots: { default: 'unitPriceCell' } },
    { field: 'cpFixedPricingRule.pricingUnit', title: '计价单位', slots: { default: 'pricingUnitCell' } },
    { field: 'cpFixedPricingRule.convertDose', title: '计价说明', slots: { default: 'convertDoseCell' } },
    { field: 'conditioningProgramSupplierName', title: '供应商' },
    { field: 'institutionName', title: '机构名称' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 150,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '查看', status: 'primary', name: 'seeDetail' },
          { content: '编辑', status: 'primary', name: 'editConfirmed' },
          { content: '删除', status: 'primary', name: 'deleteConfirmed' },
        ],
        events: {
          click({ row, rowIndex }: any, { name }: any) {
            let method;
            if (name === 'seeDetail') {
              method = seeDetail;
            } else if (name === 'editConfirmed') {
              method = editConfirmed;
            } else if (name === 'deleteConfirmed') {
              method = deleteConfirmed;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const {
  loading,
  page,
  pageSize,
  total,
  onSuccess,
  replace,
  refresh,
  remove,
  send: sendRefresh,
} = usePagination((page, size) => pageConfirmedCpMethod(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 deleteConfirmed(model: SystemItemModel, index: number) {
  const { name } = model;
  VxeUI.modal.confirm({
    title: `删除项目`,
    content: `确认要删除 ${name} 项目吗？`,
    showClose: false,
    onConfirm() {
      deleteConfirmedCpMethod(model).then(() => {
        notification.success({
          message: `删除项目: ${name}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}

function editConfirmed(model?: SystemItemModel, index?: number) {
  const addType = `itemsList`;
  if (model?.name === '健康咨询' || model?.name === '健康评估') {
    VxeUI.modal.open({
      title: model?.conditioningProgramType ?? '项目',
      height: 400,
      width: 750,
      id: `health-consultation-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(HealthEvaluation, <any>{
            data: {
              ...model,
              addType,
            },
            onSubmit(data: SystemItemModel) {
              refresh(page.value);
              VxeUI.modal.close(`health-consultation-modal`);
            },
          });
        },
      },
    });
  } else {
    VxeUI.modal.open({
      title: model?.id ? `编辑项目` : `新增项目`,
      height: 1000,
      width: 900,
      escClosable: true,
      destroyOnClose: true,
      id: `add-items-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(AddItems, <any>{
            data: { ...model, addType },
            onSubmit(data: SystemItemModel) {
              refresh(page.value);
              VxeUI.modal.close(`add-items-modal`);
            },
          });
        },
      },
    });
  }
}

function seeDetail(model?: SystemItemModel, index?: number) {
  if (model?.name === '健康咨询' || model?.name === '健康评估') {
    VxeUI.modal.open({
      title: model?.conditioningProgramType,
      height: 500,
      width: 750,
      id: `see-health-evaluation-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(seeHealthEvaluation, <any>{
            data: model,
          });
        },
      },
    });
  } else {
    const addType = 'itemsList';
    VxeUI.modal.open({
      title: '查看',
      height: 900,
      width: 1000,
      escClosable: true,
      destroyOnClose: true,
      id: `service-detail-modal`,
      remember: true,
      storage: true,
      slots: {
        default() {
          return h(ServiceDetail, <any>{
            data: {
              ...model,
              addType,
            },
            onSubmit(data: SystemItemModel) {
              refresh(page.value);
              VxeUI.modal.close(`service-detail-modal`);
            },
          });
        },
      },
    });
  }
}

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"></vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #isForWrapCell="{ row }">
          {{
            (() => {
              const isWrap = row.isForWrap === 'Y';
              const isInfer = row.isForInfer === 'Y';
              if (isWrap && isInfer) {
                return '服务包项目；调理方案项目';
              } else if (isWrap) {
                return '服务包项目';
              } else if (isInfer) {
                return '调理方案项目';
              } else {
                return '';
              }
            })()
          }}
        </template>
        <template #pricingUnitCell="{ row }">
          {{ row.cpFixedPricingRule?.pricingUnit ? row.cpFixedPricingRule?.pricingUnit : '次' }}
        </template>
        <template #unitPriceCell="{ row }">
          {{ row.pricingType === '1' ? `` : row.cpFixedPricingRule?.unitPrice }}
        </template>
        <template #convertDoseCell="{ row }">
          {{
            row.pricingType === '1'
              ? `当"穴位/经络/部位 ≤${row?.cpDynamicPricingRule ? row?.cpDynamicPricingRule[1]?.max || 0 : 0}个时，
          单价为${row?.cpDynamicPricingRule ? row?.cpDynamicPricingRule[0]?.price || 0 : 0}元，
          当"穴位/经络/部位 ＞${row?.cpDynamicPricingRule ? row?.cpDynamicPricingRule[1]?.max || 0 : 0}个时，
          单价为${row?.cpDynamicPricingRule ? row?.cpDynamicPricingRule[1]?.price || 0 : 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;
}
</style>
