<script setup lang="ts">
import type { AccountEntity, RoleGroupEntity, WorkerEntity } from '@vben/types';

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

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

import { ElMessage } from 'element-plus';
import { md5 } from 'js-md5';

import { useVbenForm, z } from '#/adapter/form';
import {
  addAccountApi,
  editAccountApi,
  getAccountDetailApi,
} from '#/api/account';
import { getRoleListApi } from '#/api/role';
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 }[]>([]);
const roleOptions = ref<{ label: string; value: string }[]>([]);

// 获取角色列表
async function fetchRoleOptions() {
  try {
    const res = await getRoleListApi({
      pageindex: 1,
      rows: 1000,
    });

    if (res && res.Data) {
      roleOptions.value = res.Data.filter(
        (item: RoleGroupEntity) => item.available === 1,
      ).map((item: RoleGroupEntity) => ({
        label: item.title,
        value: item.id.toString(),
      }));
    }
  } catch (error) {
    console.error('获取角色列表失败', error);
  }
}

// 获取职员列表
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();
  fetchRoleOptions();
});

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: 'Select',
      fieldName: 'accountgrouplist',
      label: '角色组',
      rules: z.array(z.string()).min(1, '请选择角色组'),
      componentProps: {
        placeholder: '请选择角色组',
        options: roleOptions,
        multiple: true,
        filterable: true,
        clearable: true,
        collapseTags: true,
        collapseTagsTooltip: true,
      },
    },
    // {
    //   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 processedValues = {
        ...formValues,
        accountgrouplist: Array.isArray(formValues.accountgrouplist)
          ? formValues.accountgrouplist.join(',')
          : formValues.accountgrouplist,
      };

      const apiMap = {
        create: () =>
          addAccountApi(processedValues as unknown as AccountEntity),
        edit: () =>
          editAccountApi({
            ...processedValues,
            'accountid.value': data.value.row.accountid,
          } as unknown as AccountEntity),
      };

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

      // 新增账号，设置默认密码accountpwd 123456，使用md5加密
      if (formType.value === 'create') {
        (processedValues as any).accountpwd = md5('123456');
      }

      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,
        });

        // 处理角色组数据格式：将逗号分隔的字符串转换为数组
        const processedDetailData = {
          ...detailData,
          accountgrouplist: detailData.accountgrouplist
            ? detailData.accountgrouplist.split(',').filter(Boolean)
            : [],
        };

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

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

<template>
  <Modal :title="getTitle">
    <BaseForm />
    <!-- 新增账号时的温馨提示 -->
    <div
      v-if="formType === 'create'"
      class="mt-4 rounded border-l-4 border-blue-400 bg-blue-50 p-3"
    >
      <div class="flex items-center">
        <svg
          class="mr-2 h-4 w-4 text-blue-600"
          fill="currentColor"
          viewBox="0 0 20 20"
        >
          <path
            fill-rule="evenodd"
            d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
            clip-rule="evenodd"
          />
        </svg>
        <span class="text-sm text-blue-800">
          <strong>温馨提示：</strong>新建账号的默认密码为
          <code class="rounded bg-blue-100 px-1">123456</code>
          ，请及时提醒用户修改密码。
        </span>
      </div>
    </div>
  </Modal>
</template>
