<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface';
import { enableStatusRecord } from '@/constants/business';
import {
  fetchAddUser,
  fetchDeleteUser,
  fetchDetaileUser,
  fetchEditUser,
  fetchGetRoleAllList,
  fetchGetUserList
} from '@/service/api';
import { fetchGetDepartmentList } from '@/service/api/system-department';
import { fetchGetAllChannelList } from '@/service/api/goods/store-goods';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { $t } from '@/locales';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';

const columns: NaiveUI.TableColumn<InternalRowData>[] = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'index',
    title: $t('common.index'),
    align: 'center',
    width: 64,
    render: (_, index) => index + 1
  },
  {
    key: 'username',
    title: $t('page.manage.user.userName'),
    align: 'center',
    minWidth: 100
  },
  {
    key: 'depts',
    title: '所属部门',
    align: 'center',
    width: 220,
    ellipsis: {
      tooltip: true
    },
    render(row) {
      const depts = row.depts as Recordable[];
      let text = '';
      depts.forEach(item => {
        text += `${item.deptName};`;
      });
      return text;
    }
  },

  {
    key: 'mobile',
    title: $t('page.manage.user.userPhone'),
    align: 'center',
    width: 120
  },
  {
    key: 'email',
    title: $t('page.manage.user.userEmail'),
    align: 'center',
    minWidth: 200
  },
  {
    key: 'status',
    title: $t('page.manage.user.userStatus'),
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null) {
        return null;
      }

      const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'warning'
      };

      const status = row.status as Api.Common.EnableStatus;
      const label = $t(enableStatusRecord[status]);
      return <NTag type={tagMap[status]}>{label}</NTag>;
    }
  }
];

const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'username',
        label: '用户名',
        component: 'NInput'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'userId',
    title: '用户列表',
    showAddButton: true
  }
});

async function handleDelete(row: Recordable) {
  setTableLoading(true);
  await fetchDeleteUser(row.userId);
  refresh();
}
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue, updateSchema, setModalLoading }] =
  useModalFrom({
    modalConfig: {
      title: '用户 ',
      width: 800,
      isShowHeaderText: true
    },
    formConfig: {
      schemas: [
        {
          field: 'userId',
          label: '',
          component: 'NInput',
          show: false
        },
        {
          field: 'username',
          label: '用户名',
          component: 'NInput',
          required: true,
          componentProps: {
            maxlength: 20,
            minlength: 2
          }
        },
        {
          field: 'channelIdList',
          label: '所属企业',
          component: 'ApiSelect',
          required: true,
          componentProps: {
            api: () => fetchGetAllChannelList(),
            labelFeild: 'channelName',
            valueFeild: 'id',
            multiple: true
          }
        },
        {
          field: 'deptIds',
          label: '归属部门',
          component: 'ApiTreeSelect',
          required: true,
          componentProps: {
            api: fetchGetDepartmentList,
            labelFeild: 'deptName',
            valueFeild: 'deptId',
            immediate: true,
            resultFeild: 'data',
            multiple: true
          }
        },
        {
          field: 'password',
          label: '密码',
          component: 'NInput',
          required: true,
          componentProps: {
            type: 'password',
            showPasswordOn: 'click'
          }
        },
        {
          field: 'comfirmPassword',
          label: '确认密码',
          component: 'NInput',
          required: true,
          componentProps: {
            type: 'password',
            showPasswordOn: 'click'
          }
        },
        {
          field: 'email',
          label: '邮箱',
          component: 'NInput',
          required: true,
          rules: [
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'input', 'change'],
              validator: (_fomItem, value, callback) => {
                if (!value) {
                  callback(new Error('请输入邮箱'));
                } else if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
                  callback(new Error('请输入正确的邮箱'));
                }
                return true;
              }
            }
          ]
        },
        {
          field: 'mobile',
          label: '手机号',
          component: 'NInput',
          required: true,
          componentProps: {
            maxlength: 11
          },
          rules: [
            {
              message: '请输入正确的手机号',
              trigger: ['blur', 'input'],
              validator: (_fomItem, value, callback) => {
                if (!value) {
                  callback(new Error('请输入手机号'));
                } else if (!/^1[3456789]\d{9}$/.test(value)) {
                  callback(new Error('请输入正确的手机号'));
                }
                return true;
              }
            }
          ]
        },
        {
          field: 'roleIdList',
          label: '角色',
          component: 'ApiSelect',
          required: true,
          componentProps: {
            api: () => fetchGetRoleAllList(),
            labelFeild: 'roleName',
            valueFeild: 'roleId',
            multiple: true
          }
        },
        {
          field: 'status',
          label: '状态',
          component: 'NRadioGroup',
          required: true,
          componentProps: {
            options: [
              {
                label: '启用',
                value: 1
              },
              {
                label: '禁用',
                value: 0
              }
            ]
          },
          defaultValue: 1
        }
      ],
      labelWidth: 120,
      gridProps: {
        cols: '1'
      }
    }
  });
async function handleSubmit() {
  const form = await getFieldsValue();
  if (form.userId) {
    await fetchEditUser(form as Api.SystemManage.UserModel);
  } else {
    await fetchAddUser(form as Api.SystemManage.UserModel);
  }
  closeModal();
  refresh();
}

async function edit(row: Recordable) {
  setModalLoading(true);
  openModal(row);
  const res = await fetchDetaileUser(row.userId);
  setModalLoading(false);
  setFieldsValue({ ...res.data, userId: row.userId, deptIds: res.data?.depts.map(it => it.deptId) });
  updateSchema([
    { field: 'password', required: false },
    { field: 'comfirmPassword', required: false }
  ]);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetUserList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" @click="edit(row)">编辑</NButton>
        <NPopconfirm v-if="row.userId != 1" @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost>删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
    </ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
