<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 { cleanList } from '#/api/property/clean';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

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

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

// 缓存清洁服务数据
let cleanListData: any[] = [];

const detailSchema = [
  {
    label: '劳务名称',
    fieldName: 'name',
    component: 'ApiSelect',
    componentProps: {
      api: async () => {
        const res = await cleanList({stater:1});
        cleanListData = res.rows || [];
        return res;
      },
      resultField: 'rows',
      labelField: 'name',
      valueField: 'id',
      onChange: async (value: string) => {
        // 找到选中的服务数据
        const selectedService = cleanListData.find(item => item.id === value);
        if (selectedService) {
          // 自动填充其他字段
          await formApi.setValues({
            measure: selectedService.measure,
            method: selectedService.method,
            peices: selectedService.peices,
            frequency: selectedService.frequency,
            standard: selectedService.standard,
            remark: selectedService.remark,
            stater: selectedService.stater,
          });
        }
      },
    },
    rules: 'required',
  },
      {
    label: '保洁面积',
    fieldName: 'area',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      onChange: async (value: number) => {
        const formValues = await formApi.getValues();
        if (formValues.peices && value) {
          await formApi.setValues({
            sumPeices: Number((formValues.peices * value).toFixed(2)),
          });
        }
      },
    },
  },
  {
    label: '计量单位',
    fieldName: 'measure',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '计算方式',
    fieldName: 'method',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '申报单价含税（元）',
    fieldName: 'peices',
    component: 'InputNumber',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '保洁频率',
    fieldName: 'frequency',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '保洁标准',
    fieldName: 'standard',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '备注',
    fieldName: 'remark',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
  },
  {
    label: '状态',
    fieldName: 'stater',
    component: 'Select',
    componentProps: {
      disabled: true,
      options: [
        { label: '上架', value: 1 },
        { label: '下架', value: 0 },
      ],
    },
    rules: 'required',
  },

  {
    label: '合计费用',
    fieldName: 'sumPeices',
    component: 'InputNumber',
    componentProps: {
      disabled: true,
    },
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 120,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: detailSchema,
  showDefaultActions: false,
});

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

const [BasicModal, modalApi] = useVbenModal({
  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) {
      // TODO: 获取详情数据
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    
    // 获取选中的服务名称
    const selectedService = cleanListData.find(item => item.id === data.name);
    if (selectedService) {
      data.name = selectedService.name;
      data.id = selectedService.id
    }
    console.log(data);
    
    handleClosed()
    await markInitialized();
    emit('reload', data);
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
  </BasicModal>
</template> 
<style scoped>
/* 使用 :deep() 穿透 scoped 样式，影响子组件 */
:deep(.ant-input[disabled]),
:deep(.ant-input-number-disabled .ant-input-number-input),
:deep(.ant-select-disabled .ant-select-selection-item) {
  /* 设置一个更深的颜色，可以自己调整 */
  color: rgba(0, 0, 0, 0.65) !important;
  /* 有些浏览器需要这个来覆盖默认颜色 */
  -webkit-text-fill-color: rgba(0, 0, 0, 0.65) !important;
}
</style>