<script setup lang="ts">
import type { AccountEntity, 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 {
  addAccountApi,
  editAccountApi,
  getAccountDetailApi,
} from '#/api/account';
import { getWorkerListApi } from '#/api/worker';

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

// 获取职员列表
async function fetchWorkerOptions() {
  try {
    const res = await getWorkerListApi({
      pageindex: 1,
      rows: 1000,
    });

    if (res && res.Data) {
      workerOptions.value = res.Data.map((item: WorkerEntity) => ({
        label: `${item.worker_xm}(${item.worker_gh})`,
        value: item.worker_id,
      }));
    }
  } catch (error) {
    console.error('获取职员列表失败', error);
  }
}

// 初始化时获取职员列表
onMounted(() => {
  fetchWorkerOptions();
});

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: [
    {
      component: 'Input',
      fieldName: 'accountname',
      label: '账号',
      rules: z.string().min(1, '请输入账号'),
      componentProps: {
        placeholder: '请输入账号',
      },
    },
    // {
    //   component: 'Input',
    //   fieldName: 'accountpwd',
    //   label: '密码',
    //   rules: z.string().min(1, '请输入密码'),
    //   componentProps: {
    //     type: 'password',
    //     placeholder: '请输入密码',
    //     showPassword: true,
    //   },
    // },
    {
      component: 'Switch',
      fieldName: 'accountstatus',
      label: '账号状态',
      defaultValue: 1,
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
        activeText: '可用',
        inactiveText: '不可用',
      },
    },
    {
      component: 'Input',
      fieldName: 'accountgrouplist',
      label: '角色组',
      rules: z.string().min(1, '请输入角色组'),
      componentProps: {
        placeholder: '请输入角色组',
      },
    },
    // {
    //   component: 'Input',
    //   fieldName: 'accountpopedom',
    //   label: '单一权限',
    //   componentProps: {
    //     placeholder: '请输入单一权限',
    //   },
    // },
    {
      component: 'Select',
      fieldName: 'accountworkerid',
      label: '关联职员',
      rules: z.string().min(1, '请选择关联职员'),
      componentProps: {
        placeholder: '请选择关联职员',
        options: workerOptions,
        filterable: true,
        clearable: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'accountbz',
      label: '备注',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入备注',
      },
    },
  ],
});

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: () => addAccountApi(formValues as unknown as AccountEntity),
        edit: () =>
          editAccountApi({
            ...formValues,
            'accountid.value': data.value.row.accountid,
          } as unknown as AccountEntity),
      };

      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') {
        // 新增时设置默认值
        baseFormApi.setFieldValue('accountstatus', 1);
        return;
      }

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

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

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

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