<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { rentalPlanAdd, rentalPlanInfo, rentalPlanUpdate } from '#/api/property/rentalPlan';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    }
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[70%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await rentalPlanInfo(id);
      await formApi.setValues(record);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? rentalPlanUpdate(data) : rentalPlanAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
const detailColumns = [
  { title: '序号', key: 'index' },
  { title: '产品编号', dataIndex: 'plantCode', key: 'plantCode' },
  { title: '产品名称', dataIndex: 'plantName', key: 'plantName' },
  { title: '产品分类', dataIndex: 'plantType', key: 'plantType' },
  {
    title: '图片',
    dataIndex: 'imgPath',
    key: 'imgPath',
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
  },
  { title: '租金', dataIndex: 'rent', key: 'rent' },
  { title: '备注', dataIndex: 'remark', key: 'remark' },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    customRender: ({ value }: { value: number }) =>
      value === 1 ? '上架' : '下架',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right' as const,
  },
];
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
        <!-- 添加订单详情部分、 -->
    <div class="mt-4">
      <div class="mb-2 flex items-center justify-between">
        <h3 class="text-lg font-medium">添加保洁订单详情</h3>
        <a-button type="primary" @click="handleAddDetail">
          {{ $t('pages.common.add') }}
        </a-button>
      </div>
      <Table
        :data-source="detailTable"
        :columns="detailColumns"
        :pagination="false"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.key === 'index'">
            {{ index + 1 }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Button danger @click="handleDeleteDetail(record, index)">
              删除
            </Button>
          </template>
        </template>
      </Table>
      <div>费用合计：{{ totalSumPeices }}元</div>
    </div>
  </BasicModal>
</template>

