<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import {
  fetchAddTenant,
  fetchDeleteTenant,
  fetchEditTenant,
  fetchGetTenantList,
  fetchGetTenantPackageList
} from '@/service/api/tenant';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { $t } from '@/locales';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';

const columns: NaiveUI.TableColumn<any>[] = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'index',
    title: $t('common.index'),
    align: 'center',
    width: 64,
    render: (_, index) => index + 1
  },
  {
    key: 'tenantCode',
    title: '租户编号',
    align: 'center',
    minWidth: 120
  },
  {
    key: 'contactName',
    title: '联系人',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'contactMobile',
    title: '联系电话',
    align: 'center',
    minWidth: 130
  },
  {
    key: 'tenantName',
    title: '企业名称',
    align: 'center',
    minWidth: 150
  },
  {
    key: 'expireTime',
    title: '过期时间',
    align: 'center',
    minWidth: 170
  },
  {
    key: 'status',
    title: '租户状态',
    align: 'center',
    width: 100,
    render: row => {
      if (row.status === null || row.status === undefined) {
        return null;
      }
      const tagMap: Record<number, NaiveUI.ThemeColor> = {
        1: 'success',
        0: 'error'
      };
      const labelMap: Record<number, string> = {
        1: '正常',
        0: '停用'
      };
      return <NTag type={tagMap[row.status]}>{labelMap[row.status]}</NTag>;
    }
  }
];

const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'keywords',
        label: '关键字',
        component: 'NInput',
        componentProps: {
          placeholder: '请输入租户名称/编码/域名'
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '租户列表',
    showAddButton: true,
    scrollX: 1200
  }
});

async function handleDelete(row: Recordable) {
  setTableLoading(true);
  await fetchDeleteTenant([row.id].join(','));
  refresh();
}

const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue, setModalLoading }] = useModalFrom({
  modalConfig: {
    title: '租户',
    width: 800,
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'id',
        label: '',
        component: 'NInput',
        show: false
      },
      // 基本信息
      {
        field: 'tenantName',
        label: '企业名称',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入企业名称'
        }
      },
      {
        field: 'contactName',
        label: '联系人',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入联系人'
        }
      },
      {
        field: 'contactMobile',
        label: '联系电话',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入联系电话',
          maxlength: 11
        }
      },
      // 管理员信息
      {
        field: 'adminUsername',
        label: '管理员账号',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入管理员账号'
        }
      },
      {
        field: 'adminPassword',
        label: '管理员密码',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入管理员密码',
          type: 'password',
          showPasswordOn: 'click'
        }
      },
      // 租户设置
      {
        field: 'packageId',
        label: '租户套餐',
        component: 'ApiSelect',
        required: true,
        componentProps: {
          api: () => fetchGetTenantPackageList({ pageNum: 1, pageSize: 100 }),
          labelFeild: 'packageName',
          valueFeild: 'id',
          resultFeild: 'data.list',
          placeholder: '请选择租户套餐'
        }
      },
      {
        field: 'tenantCode',
        label: '租户编号',
        component: 'NInput',
        required: true,
        componentProps: {
          placeholder: '请输入租户编号'
        }
      },
      {
        field: 'expireTime',
        label: '过期时间',
        component: 'NDatePicker',
        componentProps: {
          type: 'datetime',
          placeholder: '选择日期时间'
        } as any
      },
      // {
      //   field: 'tenantDomain',
      //   label: '绑定域名',
      //   component: 'NInput',
      //   required: true,
      //   componentProps: {
      //     placeholder: '请输入'
      //   }
      // },
      {
        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.id) {
    const { error } = await fetchEditTenant(form);
    if (!error) {
      closeModal();
      refresh();
    }
  } else {
    const { error } = await fetchAddTenant(form);
    if (!error) {
      closeModal();
      refresh();
    }
  }
}

async function edit(row: Recordable) {
  setModalLoading(true);
  openModal(row);
  setFieldsValue({ ...row });
  setModalLoading(false);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns as any" :api="fetchGetTenantList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" @click="edit(row)">编辑</NButton>
        <NPopconfirm @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>
