<script lang="ts" setup>
import type { CustomerEntity, WorkerEntity } 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 { getCustomerListApi } from '#/api/user';
import { addWorkerApi, editWorkerApi, getWorkerDetailApi } from '#/api/worker';

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

// 获取经销商列表
async function fetchChannelOptions() {
  try {
    const res = await getCustomerListApi({
      pageindex: 1,
      rows: 1000,
      'usersnature.value': '经销商', // 只获取用户性质为"经销商"的数据
    });

    if (res && res.Data) {
      channelOptions.value = res.Data.map((item: CustomerEntity) => ({
        label: item.usersname,
        value: item.usersid,
      }));
    }
  } catch (error) {
    console.error('获取经销商列表失败', error);
  }
}

// 初始化时获取经销商列表
onMounted(() => {
  fetchChannelOptions();
});

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

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

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 130,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '姓名', field: 'worker_xm' },
    // { title: '工号', field: 'worker_gh' },
    // { title: '类别', field: 'worker_lb' },
    // { title: '状态', field: 'worker_zt' },
    // { title: '所属部门', field: 'worker_ssbm' },
    // { title: '二级部门', field: 'worker_ssbm2' },
    // { title: '岗位', field: 'worker_gw' },
    // { title: '联系地址', field: 'worker_lxdz' },
    // { title: '联系电话', field: 'worker_dh' },
    // { title: '邮箱', field: 'worker_email' },
    // { title: '紧急联系人', field: 'worker_jjlxr' },
    // { title: '紧急联系电话', field: 'worker_jjlxdh' },
    // { title: '创建时间', field: 'worker_createdate' },
    // { title: '创建者', field: 'worker_create' },
    // { title: '是否绑定微信', field: 'worker_iswxbind' },

    {
      component: 'Input',
      fieldName: 'worker_xm',
      label: '姓名',
      rules: z.string().min(1, '请输入姓名'),
    },
    {
      component: 'Input',
      fieldName: 'worker_gh',
      label: '工号',
      rules: z.string().min(1, '请输入工号'),
    },
    {
      component: 'Select',
      fieldName: 'worker_lb',
      label: '类别',
      componentProps: {
        options: [
          { label: '合同工', value: '合同工' },
          { label: '实习工', value: '实习工' },
          { label: '临时工', value: '临时工' },
        ],
      },
      rules: z.string().min(1, '请选择类别'),
    },
    {
      component: 'Select',
      fieldName: 'worker_zt',
      label: '状态',
      componentProps: {
        options: [
          { label: '在职', value: '在职' },
          { label: '离职', value: '离职' },
          { label: '退假', value: '退假' },
        ],
      },
      rules: z.string().min(1, '请选择状态'),
    },
    // {
    //   component: 'Input',
    //   fieldName: 'worker_ssbm',
    //   label: '所属部门',
    //   rules: z.string().min(1, '请输入所属部门'),
    // },
    // {
    //   component: 'Input',
    //   fieldName: 'worker_ssbm2',
    //   label: '二级部门',
    // },
    {
      component: 'Input',
      fieldName: 'worker_gw',
      label: '岗位',
    },
    {
      component: 'Input',
      fieldName: 'worker_lxdz',
      label: '联系地址',
    },
    {
      component: 'Input',
      fieldName: 'worker_dh',
      label: '联系电话',
      rules: z.string().min(1, '请输入联系电话'),
    },
    {
      component: 'Input',
      fieldName: 'worker_email',
      label: '邮箱',
    },
    {
      component: 'Input',
      fieldName: 'worker_jjlxr',
      label: '紧急联系人',
    },
    {
      component: 'Input',
      fieldName: 'worker_jjlxdh',
      label: '紧急联系电话',
    },
    {
      component: 'Select',
      fieldName: 'worker_userid',
      label: '关联经销商',
      componentProps: {
        placeholder: '请选择关联经销商',
        options: channelOptions,
        filterable: true,
        clearable: true,
      },
    },
  ],
});

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: () => addWorkerApi(formValues as unknown as WorkerEntity),
        edit: () =>
          editWorkerApi({
            ...formValues,
            'worker_id.value': data.value.row.worker_id,
          } as unknown as WorkerEntity),
      };

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

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

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

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