import { Button, Form, Input, notification, Select } from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import { stringify } from 'qs';
import type React from 'react';
import { useImperativeHandle, useState } from 'react';
import ModalPlugin from '@/components/ModalPlugin';
import { stateOptions, userSexOptions } from '@/configs/usersConfig';
import { UserServices } from '@/services/UserServices';
import type { IRef } from '@/utils/type';
import { useRequest } from '@/utils/useRequest';

interface IProps extends IRef {
  onCallback?: () => void;
}

export type IUserEditModalType = {
  show: (data?: any) => void;
};

export const UserEditModal: React.FC<IProps> = (props) => {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [form] = Form.useForm();
  const [data, setData] = useState<any>(null);

  // 请求成功回调
  const success = (res: any) => {
    if (res.err_code === 0) {
      notification.success({ message: '保存成功' });
      props.onCallback?.();
      setOpen(false);
      form.resetFields(); // 提交成功重置表单
    }
  };

  const { loading: addLoading, request: addRequest } = useRequest(UserServices.add, { onSuccess: success });
  const { loading: editLoading, request: editRequest } = useRequest(UserServices.edit, { onSuccess: success });

  const save = async () => {
    try {
      const values = await form.validateFields();
      // 编辑场景带上主键
      if (data?.user_id) {
        values.user_id = data.user_id;
        editRequest(stringify(values));
      } else {
        addRequest(stringify(values));
      }
    } catch (error) {
      console.log('表单验证未通过', error);
    }
  };

  useImperativeHandle(props.ref, () => ({
    show: (data?: any) => {
      setTitle(data ? `${data.login_name} 编辑` : '新增');
      setOpen(true);
      setData(data);

      if (data) {
        // 编辑场景初始化表单
        form.setFieldsValue({
          login_name: data.login_name,
          user_phone: data.user_phone,
          user_mail: data.user_mail,
          nick_name: data.nick_name,
          password: '', // 密码编辑可选
          comments: data.comments,
          user_sex: String(data.user_sex),
          state: String(data.state),
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          user_sex: '1',
          state: '1',
        });
      }
    },
  }));

  return (
    <ModalPlugin
      open={open}
      onCancel={() => setOpen(false)}
      title={title}
      footer={[
        <Button key='cancel' onClick={() => setOpen(false)}>
          取消
        </Button>,
        <Button key='save' type='primary' loading={addLoading || editLoading} onClick={save}>
          保存
        </Button>,
      ]}
    >
      <Form form={form} labelCol={{ style: { width: window?.dfConfig?.language === 'zh-cn' ? 80 : 120 } }}>
        <Form.Item
          label='用户名'
          name='login_name'
          required
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 2, message: '最少2字符' },
            { max: 20, message: '最多20字符' },
          ]}
        >
          <Input allowClear placeholder='请填写用户名' maxLength={20} showCount />
        </Form.Item>

        <Form.Item
          label='昵称'
          name='nick_name'
          rules={[
            { min: 2, message: '最少2字符' },
            { max: 20, message: '最多20字符' },
          ]}
        >
          <Input allowClear placeholder='请填写昵称' maxLength={20} showCount />
        </Form.Item>

        <Form.Item
          label='手机号'
          name='user_phone'
          required
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
          ]}
        >
          <Input allowClear placeholder='请填写手机号' maxLength={11} showCount />
        </Form.Item>

        <Form.Item label='邮箱' name='user_mail' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
          <Input allowClear placeholder='请填写邮箱' />
        </Form.Item>

        <Form.Item
          label='密码'
          name='password'
          tooltip={data ? undefined : '不填写则系统自动生成初始密码'}
          //help={<div style={{ marginBottom: 6, fontSize: 12, color: '#999' }}>不填写则系统自动生成初始密码</div>}
          rules={[{ min: 6, max: 18, message: '密码需6~18位' }]}
        >
          <Input.Password allowClear placeholder={data ? '不修改请留空' : '请填写密码'} />
        </Form.Item>

        {!data?.user_id && (
          <Form.Item
            label='企业名'
            name='company_name'
            rules={[
              { min: 2, message: '最少2字符' },
              { max: 20, message: '最多20字符' },
            ]}
          >
            <Input allowClear placeholder='请填写企业名' />
          </Form.Item>
        )}

        <Form.Item label={'性别'} name='user_sex'>
          <Select options={userSexOptions} placeholder='请选择性别' />
        </Form.Item>

        <Form.Item label={'状态'} name='state'>
          <Select options={stateOptions} placeholder='请选择状态' />
        </Form.Item>

        <Form.Item label='备注' name='comments'>
          <TextArea allowClear maxLength={200} showCount />
        </Form.Item>
      </Form>
    </ModalPlugin>
  );
};
