import {
  MyButtons,
  MyColumns,
  MyImportModal,
  MyPageContainer,
  MyProTableProps,
  renderTextHelper,
  useCurrentPermissions,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { CompanyEmployeesTypeEnum } from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { Dropdown, Space } from 'antd';
import Change from './modals/Change';
import CompletePhone from './modals/CompletePhone';
import EmployeeCreate from './modals/EmployeeCreate';
import EmployeeUpdate from './modals/EmployeeUpdate';
import Role from './modals/Role';

export default function Index({ title = '员工管理' }) {
  const getCurrentPermissions = useCurrentPermissions();
  let toolBarRender = (action: any) => {
    return getCurrentPermissions({
      create: (
        <EmployeeCreate key="Create" reload={action?.reload} title="员工" />
      ),
      export: (
        <MyImportModal
          key="ImportHouse"
          title="导入外部人员"
          type="default"
          size="middle"
          templateApi={Apis.Company.CompanyEmployees.DownloadTemplate}
          importApi={Apis.Company.CompanyEmployees.Import}
          reload={action?.reload}
        />
      ),
    });
  };
  let tableRender = (item: any, action: any) => {
    let permissions = getCurrentPermissions({
      update: (
        <EmployeeUpdate item={item} reload={action?.reload} title={title} />
      ),
      change: <Change item={item} reload={action?.reload} title={title} />,
    });
    let permissionsSpace = getCurrentPermissions({
      Role: {
        key: '1',
        label: <Role item={item} reload={action?.reload} title={title} />,
      },
      resetPassword: {
        key: '2',
        label: (
          <MyButtons.Default
            title="重置密码"
            type="default"
            isConfirm={true}
            description={`确定要重置用户「${item.name}」的密码为「Gc#123」吗？`}
            onConfirm={() =>
              Apis.Company.CompanyEmployees.ResetPassword({
                id: item.id,
                password: 'Gc#123',
              }).then(() => action?.reload())
            }
          />
        ),
      },
      delete: {
        key: '3',
        label: (
          <MyButtons.Delete
            onConfirm={() =>
              Apis.Company.CompanyEmployees.Delete({ id: item.id }).then(() =>
                action?.reload(),
              )
            }
          />
        ),
      },
    });
    let Others = (
      <Dropdown menu={{ items: permissionsSpace }} trigger={['click']}>
        <MyButtons.Default title="更多" />
      </Dropdown>
    );
    return [...permissions, ...[Others]];
  };
  return (
    <MyPageContainer
      enableTabs
      tabKey="employees-list"
      tabLabel={title}
      title={title}
    >
      <ProTable
        {...MyProTableProps.props}
        // search={false}
        headerTitle="员工列表"
        tooltip="通过企微同步的员工信息的修改，需在企微修改后，同步到系统，才能生效。"
        request={async (params, sort) =>
          MyProTableProps.request(
            params,
            sort,
            Apis.Company.CompanyEmployees.List,
          )
        }
        toolBarRender={(action) => [
          <MyButtons.Default
            key="sync_wechat_employees"
            type="primary"
            size="middle"
            title="企微同步"
            isConfirm={true}
            description="确定要执行企微同步操作吗？"
            onConfirm={async () => {
              try {
                await Apis.Company.CompanyEmployees.SyncWechatEmployees();
                action?.reload?.();
              } catch (error) {
                console.error('同步企微信息失败:', error);
              }
            }}
          />,
          <CompletePhone
            key="CompletePhone"
            reload={action?.reload}
            title="补全手机号"
          />,
          toolBarRender(action),
        ]}
        columns={[
          MyColumns.ID({
            search: false,
          }),
          {
            title: '所在组织',
            dataIndex: 'organization_path',
            search: {
              transform: (value) => {
                return { organization_name: value };
              },
            },
          },
          {
            title: '姓名',
            dataIndex: 'name',
          },
          {
            title: '手机号',
            dataIndex: 'phone',
          },
          {
            title: '角色',
            dataIndex: 'roles',
            renderText: renderTextHelper.TagList,
            hideInSearch: true,
          },
          {
            title: '岗位',
            dataIndex: ['position', 'name'],
            search: false,
          },
          MyColumns.EnumTag({
            title: '来源',
            dataIndex: 'type',
            valueEnum: CompanyEmployeesTypeEnum,
          }),
          MyColumns.SoftDelete({
            title: '启/禁用',
            onRestore: Apis.Company.CompanyEmployees.Restore,
            onSoftDelete: Apis.Company.CompanyEmployees.SoftDelete,
            search: false,
            setPermissions: getCurrentPermissions({
              enableDisable: true,
            }),
          }),
          MyColumns.UpdatedAt(),
          // MyColumns.CreatedAt(),
          MyColumns.Option({
            render: (_, item: any, index, action) => (
              <Space key={index}>
                <>{tableRender(item, action)}</>
              </Space>
            ),
          }),
        ]}
      />
    </MyPageContainer>
  );
}
