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

import { computed, onMounted, ref } from 'vue';

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

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { getScqyListApi } from '#/api/scqy';
import {
  addCustomerApi,
  editCustomerApi,
  getCustomerDetailApi,
} from '#/api/user';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');
const scqyOptions = ref<{ label: string; value: string }[]>([]);

const titleMap = {
  create: '新增客户',
  detail: '客户详情',
  edit: '编辑客户',
} as const;

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

const scqySelectOptions = computed(() => scqyOptions.value);

// 获取生产企业列表
const fetchScqyList = async () => {
  try {
    const { Total, Data } = await getScqyListApi({ pageindex: 1, rows: 999 });
    const list = Data || [];
    if (Total > 0) {
      scqyOptions.value = list.map((item: any) => ({
        label: item.scqyinfomc,
        value: item.scqyinfoid,
      }));
    }
    console.log('获取生产企业列表:', scqyOptions.value);
  } catch (error) {
    console.error('获取生产企业列表失败:', error);
  }
};

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 130,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '用户名称', field: 'usersname' },
    // { title: '用户性质', field: 'usersnature' },
    // { title: '用户类型', field: 'userstype' },
    // { title: '用户证件号码', field: 'usersidcardnumber' },
    // { title: '用户开户银行名称', field: 'usersbankname' },
    // { title: '用户开户银行账号', field: 'usersbanknumber' },
    // { title: '用户手机号', field: 'usersphone' },
    // { title: '用户邮箱', field: 'usersemail' },
    // { title: '用户地址', field: 'usersaddress' },
    // { title: '用户联系手机号', field: 'userscontactphone' },
    // { title: '用户联系邮箱', field: 'userscontactemail' },
    // { title: '用户联系地址', field: 'userscontactaddress' },
    // { title: '备注', field: 'usersbz' },
    // { title: '用户微信openid', field: 'usersopenid' },
    // { title: '用户是否实名', field: 'usersauthstatus' },
    // { title: '用户创建时间', field: 'usersdate' },
    // { title: '用户类型', field: 'userstype' },
    // { title: '法人代表电话(座机)', field: 'usersfrdbdh' },
    // { title: '法人代表手机号', field: 'usersfrdbsjh' },
    // { title: '销售手机号', field: 'usersxssjh' },
    // { title: '销售电话(座机)', field: 'usersxsdh' },
    // { title: '社会统一企业代码', field: 'usersshtyxydm' },
    // { title: '企业注册地', field: 'userszcd' },
    // { title: '传真', field: 'userscz' },
    // { title: '备注', field: 'usersbz' },

    {
      component: 'Input',
      fieldName: 'usersname',
      label: '用户名称',
      componentProps: {
        placeholder: '请输入用户名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入用户名称' }),
    },
    {
      component: 'Select',
      fieldName: 'usersnature',
      label: '用户性质',
      componentProps: {
        placeholder: '请选择用户性质',
        allowClear: true,
        options: [
          { label: '购机者', value: '购机者' },
          { label: '经销商', value: '经销商' },
        ],
      },
      rules: z.string().min(1, { message: '请选择用户性质' }),
    },
    {
      component: 'Select',
      fieldName: 'userstype',
      label: '用户类型',
      defaultValue: '个人',
      componentProps: {
        placeholder: '请选择用户类型',
        allowClear: true,
        options: [
          { label: '个人', value: '个人' },
          { label: '企业', value: '企业' },
        ],
      },
      rules: z.string().min(1, { message: '请选择用户类型' }),
    },
    // 个人用户显示身份证号
    {
      component: 'Input',
      fieldName: 'usersidcardnumber',
      label: '身份证号码',
      componentProps: {
        placeholder: '请输入身份证号码',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入身份证号码' }),
      dependencies: {
        if(values) {
          return values.userstype === '个人';
        },
        triggerFields: ['userstype'],
      },
    },
    // 企业用户显示的字段
    {
      component: 'Input',
      fieldName: 'usersshtyxydm',
      label: '统一社会信用代码',
      componentProps: {
        placeholder: '请输入统一社会信用代码',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入统一社会信用代码' }),
      dependencies: {
        if(values) {
          return values.userstype === '企业';
        },
        triggerFields: ['userstype'],
      },
    },
    {
      component: 'Input',
      fieldName: 'userszcd',
      label: '企业注册地',
      componentProps: {
        placeholder: '请输入企业注册地',
        allowClear: true,
      },
      dependencies: {
        if(values) {
          return values.userstype === '企业';
        },
        triggerFields: ['userstype'],
      },
    },
    {
      component: 'Input',
      fieldName: 'usersfrdbdh',
      label: '法人代表电话(座机)',
      componentProps: {
        placeholder: '请输入法人代表电话',
        allowClear: true,
      },
      dependencies: {
        if(values) {
          return values.userstype === '企业';
        },
        triggerFields: ['userstype'],
      },
    },
    {
      component: 'Input',
      fieldName: 'usersfrdbsjh',
      label: '法人代表手机号',
      componentProps: {
        placeholder: '请输入法人代表手机号',
        allowClear: true,
      },
      dependencies: {
        if(values) {
          return values.userstype === '企业';
        },
        triggerFields: ['userstype'],
      },
    },
    // 生产企业选择
    {
      component: 'Select',
      fieldName: 'usersscqyid',
      label: '生产企业',
      componentProps: {
        placeholder: '请选择生产企业',
        allowClear: true,
        options: scqySelectOptions,
      },
      rules: z.string().min(1, { message: '请选择生产企业' }),
      dependencies: {
        if(values) {
          return values.usersnature === '经销商';
        },
        triggerFields: ['usersnature'],
      },
    },
    // 通用字段
    {
      component: 'Input',
      fieldName: 'usersbankname',
      label: '开户银行名称',
      componentProps: {
        placeholder: '请输入开户银行名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入开户银行名称' }),
    },
    {
      component: 'Input',
      fieldName: 'usersbanknumber',
      label: '开户银行账号',
      componentProps: {
        placeholder: '请输入开户银行账号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入开户银行账号' }),
    },
    {
      component: 'Input',
      fieldName: 'usersphone',
      label: '手机号',
      componentProps: {
        placeholder: '请输入手机号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入手机号' }),
    },
    {
      component: 'Input',
      fieldName: 'usersemail',
      label: '邮箱',
      componentProps: {
        placeholder: '请输入邮箱',
        allowClear: true,
      },
      rules: z.string().email({ message: '请输入正确的邮箱格式' }),
    },
    {
      component: 'Input',
      fieldName: 'usersaddress',
      label: '地址',
      componentProps: {
        placeholder: '请输入地址',
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'userscz',
      label: '传真',
      componentProps: {
        placeholder: '请输入传真',
        allowClear: true,
      },
      dependencies: {
        if(values) {
          return values.userstype === '企业';
        },
        triggerFields: ['userstype'],
      },
    },
    {
      component: 'Input',
      fieldName: 'usersbz',
      label: '备注',
      componentProps: {
        placeholder: '请输入备注',
        allowClear: true,
        type: 'textarea',
        rows: 4,
      },
    },
  ],
});

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

    try {
      const apiMap = {
        create: () => addCustomerApi(formValues as unknown as CustomerEntity),
        edit: () =>
          editCustomerApi({
            ...formValues,
            'usersid.value': data.value.row.usersid,
          } as unknown as CustomerEntity),
      };

      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 getCustomerDetailApi({
          usersid: data.value.row.usersid,
        });

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

      modalApi.setState({ loading: false });
    }
  },
});

// 组件挂载时获取生产企业列表
onMounted(() => {
  fetchScqyList();
});
</script>

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