import { DictValueEnumObj } from '@/components/DictTag';
import KFModal from '@/components/KFModal';
import {
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Form } from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect } from 'react';

export type UserFormData = Record<string, unknown> & Partial<API.System.User>;

export type UserFormProps = {
  onCancel: (flag?: boolean, formVals?: UserFormData) => void;
  onSubmit: (values: UserFormData) => Promise<void>;
  open: boolean;
  values: Partial<API.System.User>;
  sexOptions: DictValueEnumObj;
  statusOptions: DictValueEnumObj;
  postIds: number[];
  posts: string[];
  roleIds: number[];
  roles: string[];
  depts: DataNode[];
};

const UserForm: React.FC<UserFormProps> = (props) => {
  const [form] = Form.useForm();
  // const userId = Form.useWatch('userId', form);
  const { sexOptions, statusOptions } = props;
  const { roles, posts, depts } = props;
  const formLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  useEffect(() => {
    form.resetFields();
    form.setFieldsValue({
      userId: props.values.userId,
      deptId: props.values.deptId,
      postIds: props.postIds,
      roleIds: props.roleIds,
      userName: props.values.userName ?? '',
      nickName: props.values.nickName,
      email: props.values.email,
      phonenumber: props.values.phonenumber,
      sex: props.values.sex || '0',
      avatar: props.values.avatar,
      status: props.values.status || Object.keys(statusOptions)[0],
      delFlag: props.values.delFlag,
      loginIp: props.values.loginIp,
      loginDate: props.values.loginDate,
      remark: props.values.remark,
      // gitLinkUsername: props.values.gitLinkUsername,
      // gitLinkPassword: props.values.gitLinkPassword,
      credit: props.values.credit,
    });
  }, [form, props, statusOptions]);

  const intl = useIntl();
  const handleOk = () => {
    form.submit();
  };
  const handleCancel = () => {
    props.onCancel();
  };
  const handleFinish = async (values: Record<string, any>) => {
    const params = {
      ...values,
      userId: props.values.userId,
      originPassword: props.values.originPassword,
    };
    props.onSubmit(params as UserFormData);
  };

  return (
    <KFModal
      width={680}
      title={intl.formatMessage({
        id: 'system.user.title',
        defaultMessage: '编辑用户信息',
      })}
      open={props.open}
      destroyOnClose
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <ProForm
        grid={true}
        form={form}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish}
        {...formLayout}
        size="large"
        labelAlign="right"
        autoComplete="off"
      >
        <ProFormText
          name="nickName"
          label={intl.formatMessage({
            id: 'system.user.nick_name',
            defaultMessage: '用户昵称',
          })}
          placeholder="请输入用户昵称"
          colProps={{ xs: 24, md: 12, xl: 12 }}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="请输入用户昵称！" defaultMessage="请输入用户昵称！" />,
            },
          ]}
        />
        <ProFormTreeSelect
          name="deptId"
          label={intl.formatMessage({
            id: 'system.user.dept_name',
            defaultMessage: '部门',
          })}
          request={async () => {
            return depts;
          }}
          placeholder="请输入用户部门"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="请输入用户部门！" defaultMessage="请输入用户部门！" />,
            },
          ]}
        />
        <ProFormText
          name="phonenumber"
          label={intl.formatMessage({
            id: 'system.user.phonenumber',
            defaultMessage: '手机号码',
          })}
          placeholder="请输入手机号码"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="请输入手机号码！" defaultMessage="请输入手机号码！" />,
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: (
                <FormattedMessage
                  id="请输入正确的手机号码！"
                  defaultMessage="请输入正确的手机号码！"
                />
              ),
            },
          ]}
        />
        <ProFormText
          name="email"
          label={intl.formatMessage({
            id: 'system.user.email',
            defaultMessage: '用户邮箱',
          })}
          placeholder="请输入用户邮箱"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="请输入用户邮箱！" defaultMessage="请输入用户邮箱！" />,
            },
            {
              type: 'email',
              message: (
                <FormattedMessage
                  id="请输入正确的邮箱地址！"
                  defaultMessage="请输入正确的邮箱地址！"
                />
              ),
            },
          ]}
        />
        <ProFormText
          name="userName"
          label={intl.formatMessage({
            id: 'system.user.user_name',
            defaultMessage: '用户账号',
          })}
          disabled={!!props.values.userId}
          placeholder="请输入用户账号"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: true,
            },
            {
              pattern: /^[a-zA-Z][a-zA-Z0-9]{3,14}$/,
              message: '用户账号长度为4 ~ 15位，且必须以字母开头，只支持字母和数字',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          label={intl.formatMessage({
            id: 'system.user.password',
            defaultMessage: '密码',
          })}
          placeholder="请输入密码"
          colProps={{ md: 12, xl: 12 }}
          fieldProps={{
            autoComplete: 'new-password',
          }}
          allowClear
          rules={
            props.values.userId
              ? []
              : [
                  { required: true, message: '请输入密码！' },
                  {
                    pattern: /^[A-Za-z0-9!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]{8,16}$/,
                    message: '密码长度为8 ~ 16位，只支持字母数字和符号',
                  },
                ]
          }
        />
        <ProFormSelect
          valueEnum={sexOptions}
          name="sex"
          label={intl.formatMessage({
            id: 'system.user.sex',
            defaultMessage: '用户性别',
          })}
          placeholder="请输入用户性别"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: false,
              message: <FormattedMessage id="请输入用户性别！" defaultMessage="请输入用户性别！" />,
            },
          ]}
        />
        <ProFormRadio.Group
          valueEnum={statusOptions}
          name="status"
          label={intl.formatMessage({
            id: 'system.user.status',
            defaultMessage: '帐号状态',
          })}
          placeholder="请输入帐号状态"
          colProps={{ md: 12, xl: 12 }}
          rules={[
            {
              required: false,
              message: <FormattedMessage id="请输入帐号状态！" defaultMessage="请输入帐号状态！" />,
            },
          ]}
        />
        <ProFormSelect
          name="postIds"
          mode="multiple"
          label={intl.formatMessage({
            id: 'system.user.post',
            defaultMessage: '岗位',
          })}
          options={posts}
          placeholder="请选择岗位"
          colProps={{ md: 12, xl: 12 }}
          rules={[{ required: true, message: '请选择岗位!' }]}
        />
        <ProFormSelect
          name="roleIds"
          mode="multiple"
          label={intl.formatMessage({
            id: 'system.user.role',
            defaultMessage: '角色',
          })}
          options={roles}
          placeholder="请选择角色"
          colProps={{ md: 12, xl: 12 }}
          rules={[{ required: true, message: '请选择角色!' }]}
        />
        {/* <ProFormText
          name="gitLinkUsername"
          label="Git 用户名"
          placeholder="请输入 Git 用户名"
          colProps={{ xs: 24, md: 12, xl: 12 }}
          rules={[
            {
              required: true,
              message: '请输入 Git 用户名！',
            },
          ]}
        />
        <ProFormText.Password
          name="gitLinkPassword"
          label="Git 密码"
          placeholder="请输入 Git 密码"
          colProps={{ xs: 24, md: 12, xl: 12 }}
          fieldProps={{
            autoComplete: 'new-password',
          }}
          rules={props.values.userId ? [] : [{ required: true, message: '请输入 Git 密码！' }]}
        /> */}
        <ProFormDigit
          name="credit"
          label="算力积分"
          placeholder="请输入算力积分"
          colProps={{ xs: 24, md: 12, xl: 12 }}
          max={100000}
          min={0}
          rules={[
            {
              required: true,
              message: '请输入算力积分',
            },
            {
              type: 'number',
              min: 0,
              max: 100000,
              message: '请输入0 ~ 100000之间的数',
            },
          ]}
        />
        <ProFormTextArea
          name="remark"
          label={intl.formatMessage({
            id: 'system.user.remark',
            defaultMessage: '备注',
          })}
          placeholder="请输入备注"
          colProps={{ md: 24, xl: 24 }}
          {...formItemLayout}
          rules={[
            {
              required: false,
              message: <FormattedMessage id="请输入备注！" defaultMessage="请输入备注！" />,
            },
          ]}
        />
      </ProForm>
    </KFModal>
  );
};

export default UserForm;
