<script setup lang="ts">
import { ref } from 'vue';
import Institution from '@/components/institution.vue';
import SupplyProject from '@/components/SupplyProject.vue';
import EditSupplier from '@/components/EditSupplier.vue';
import type { SupplierModel, SupplierQuery } from '@/model/care.model';
import { businessStatus } from '@/model/options';
// 接口数据
import { supplierMethod, supplierDeleteMethod } from '@/request/api/care.api';
import { branchMethod } from '@/request/api/system.api';
import { getDictionaryMethod } from '@/request/api/dictionary.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 { data: branch, loading: branchLoading } = useRequest(branchMethod);

const projectList = ref<Array<{ label: string; value: string }>>([]);
const model = shallowRef<SupplierQuery>();
const searchFormProps = reactive<VxeFormProps<SupplierQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {},
  items: [
    {
      field: 'name',
      title: '供应商',
      span: 6,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入' } },
    },
    {
      field: 'collaborateDeptId',
      title: '合作机构',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    },
    {
      field: 'conditioningProgramTypes',
      title: '供应项目',
      span: 6,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择',
          options: computed(() => projectList.value),
          optionProps: {
            value: 'value',
            label: 'label',
          },
          multiple: true,
          collapseTags: true,
          clearable: true,
        },
      },
    },
    {
      field: 'businessStatus',
      title: '营业状态',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          placeholder: '请选择',
          options: businessStatus,
        },
      },
    },

    {
      span: 4,
      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') {
              // 新增
              editSupplier();
            }
          },
        },
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<SupplierQuery> = {
  // 查询随访计划
  submit({ data }) {
    if (data.collaborateDeptId !== undefined && data.collaborateDeptId !== null) {
      data.collaborateDeptId = Number(data.collaborateDeptId);
    }
    model.value = { ...data };
  },
  // 重置
  reset({ data }) {
    model.value = { ...data };
  },
};
const gridRef = ref<VxeGridInstance<SupplierModel>>();
const gridOptions = reactive<VxeGridProps<SupplierModel>>({
  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: [
    { field: 'name', title: '供应商' },
    { field: 'detailAddress', title: '地址' },
    { field: 'kahuna', title: '负责人' },
    { field: 'phone', title: '联系电话' },
    { field: 'profitSharing', title: '分账比例' },
    { field: 'businessStatus', title: '营业状态' ,slots: { default: 'businessStatusCell' }},
    {
      field: 'collaborateDepts',
      title: '合作机构',
      align: 'center',
      width: 120,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [{ content: '查看', status: 'primary', name: 'seeInstitution' }],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'seeInstitution') {
              method = seeInstitution;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
    {
      field: 'projectAction',
      title: '供应项目',
      align: 'center',
      width: 120,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [{ content: '查看', status: 'primary', name: 'supplyProject' }],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'supplyProject') {
              method = seeSupplyProject;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '编辑', status: 'primary', name: 'editSupplier' },
          { content: '删除', status: 'error', name: 'deleteSupplier' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'editSupplier') {
              method = editSupplier;
            } else if (name === 'deleteSupplier') {
              method = deleteSupplier;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination((page, size) => supplierMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: false,
});
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});
onBeforeMount(async () => {
  if (model.value?.id) {
    model.value = { ...model.value };
  }
  try {
    const res = await getDictionaryMethod('condition_type');
    if (res?.length > 0) {
      projectList.value = res;
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
  }
});
onMounted(() => {
  model.value = toRaw(searchFormProps.data);
});

function deleteSupplier(model: SupplierModel, index: number) {
  const { name } = model;
  VxeUI.modal.confirm({
    title: `删除供应商`,
    content: `确认要删除 ${name} 供应商吗？`,
    showClose: false,
    onConfirm() {
      supplierDeleteMethod(model).then(() => {
        notification.success({
          message: `删除供应商: ${name}`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}
function seeSupplyProject(model?: SupplierModel, index?: number) {
  VxeUI.modal.open({
    id: 'supplyProject-modal',
    title: '供应项目',
    height: 700,
    width:1000,
    position: {
      top: Math.min(100, window.innerHeight * 0.1),
    },
    escClosable: true,
    destroyOnClose: true,
    slots: {
      default() {
        return h(SupplyProject, <any>{
          data: model,
        });
      },
    },
  });
}
function seeInstitution(model?: SupplierModel, index?: number) {
  VxeUI.modal.open({
    id: 'institution-modal',
    title: '合作机构',
    height: 700,
    width: 850,
    position: {
      top: Math.min(100, window.innerHeight * 0.1),
    },
    escClosable: true,
    destroyOnClose: true,
    slots: {
      default() {
        return h(Institution, <any>{
          data: model?.collaborateDepts,
        });
      },
    },
  });
}
function editSupplier(model?: SupplierModel, index?: number) {
  VxeUI.modal.open({
    id: 'supplier-modal',
    title: model?.id ? `修改供应商` : `新增供应商`,
    height: 850,
    width: 850,
    position: {
      top: Math.min(100, window.innerHeight * 0.1),
    },
    escClosable: true,
    destroyOnClose: true,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditSupplier, <any>{
          data: model,
          onSubmit(data: SupplierModel) {
            refresh(page.value);
            VxeUI.modal.close(`supplier-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 #businessStatusCell="{ row }">
          <span>{{ row.businessStatus === '1' ? '营业' : row.businessStatus === '2' ? '休息' : row.businessStatus === '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);
}
</style>
