<script lang="ts" setup>
import type { ScqyEntity } from '@vben/types';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { addScqyApi, editScqyApi, getScqyDetailApi } from '#/api/scqy';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');

const titleMap = {
  create: '新增生产企业',
  detail: '生产企业详情',
  edit: '编辑生产企业',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 140,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '生产企业名称', field: 'scqyinfomc' },
    // { title: '生产企业地址', field: 'scqyinfoaddress' },
    // { title: '生产企业法人姓名', field: 'scqyinfofrmc' },
    // { title: '生产企业电子邮箱', field: 'scqyinfomail' },
    // { title: '生产企业销售联系人', field: 'scqyinfoxsmc' },
    // { title: '生产企业销售联系手机号', field: 'scqyinfoxsphone' },
    {
      component: 'Input',
      fieldName: 'scqyinfomc',
      label: '企业名称',
      componentProps: {
        placeholder: '请输入生产企业名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入生产企业名称' }),
    },
    {
      component: 'Input',
      fieldName: 'scqyinfoaddress',
      label: '企业地址',
      componentProps: {
        placeholder: '请输入生产企业地址',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入生产企业地址' }),
    },
    {
      component: 'Input',
      fieldName: 'scqyinfofrmc',
      label: '法人姓名',
      componentProps: {
        placeholder: '请输入生产企业法人姓名',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入生产企业法人姓名' }),
    },
    {
      component: 'Input',
      fieldName: 'scqyinfomail',
      label: '电子邮箱',
      componentProps: {
        placeholder: '请输入生产企业电子邮箱',
        allowClear: true,
      },
      rules: z.string().email({ message: '请输入正确的电子邮箱格式' }),
    },
    {
      component: 'Input',
      fieldName: 'scqyinfoxsmc',
      label: '销售联系人',
      componentProps: {
        placeholder: '请输入生产企业销售联系人',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入生产企业销售联系人' }),
    },
    {
      component: 'Input',
      fieldName: 'scqyinfoxsphone',
      label: '销售联系手机号',
      componentProps: {
        placeholder: '请输入生产企业销售联系手机号',
        allowClear: true,
      },
      rules: z
        .string()
        .regex(/^1[3-9]\d{9}$/, { message: '请输入正确的手机号格式' }),
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-7/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      // 调用新增或编辑接口
      const apiMap = {
        create: () => addScqyApi(validate.values as ScqyEntity),
        edit: () =>
          editScqyApi({
            ...validate.values,
            'scqyinfoid.value': data.value.row.scqyinfoid,
          } as any),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');

      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      formType.value = data.value.formType;

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      if (data.value.formType === 'create') {
        return;
      }

      try {
        modalApi.setState({ loading: true });
        const detailData = await getScqyDetailApi({
          scqyinfoid: data.value.row.scqyinfoid,
        });

        baseFormApi.setValues(detailData);
      } catch {
        // console.log(error);
      }

      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
