import React, { useState } from 'react';
import { Col, Form, Input, message, Modal, Row, Upload } from 'antd';
import { createUser, editUser } from '@/services/setting';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import md5 from 'js-md5';

interface userEditPros {
  visible: boolean;
  editCallback: () => void;
  params: any;
}

/**
 * 用户管理编辑
 * @param props
 * @constructor
 */
const Edit: React.FC<userEditPros> = (props) => {
  const { visible, editCallback, params } = props;
  const [form] = Form.useForm();
  const uploadHeaders = { Authorization: `${localStorage.getItem('token')}` };
  const [fileUrl, setFileUrl] = useState(params && params.photo ? params.photo : '');
  const [loading, setLoading] = useState(false);

  const getBase64 = (img: any) => {
    const reader = new FileReader();
    reader.readAsDataURL(img);
    reader.onloadend = () => {
      const url = reader.result;
      setFileUrl(url);
    };
  };

  const filesProps: UploadProps = {
    maxCount: 1,
    action: '/web/v1/files',
    headers: uploadHeaders,
    listType: 'picture-card',
    showUploadList: false,
    onChange(info) {
      if (info.file.status === 'uploading') {
        setLoading(true);
        return;
      }
      if (info.file.status === 'done') {
        setLoading(false);
        getBase64(info.file.originFileObj);
      } else if (info.file.status === 'error') {
        setLoading(false);
        message.error('文件上传失败');
      }
    },
  };

  /**
   * 确定
   */
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        if (values?.photo) {
          data.photo = values?.photo?.file?.response?.data?.url;
        }
        if (values?.password) {
          data.password = md5(values.password);
        }
        if (params) {
          data.record_id = params.record_id;
          //  编辑
          editUser(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('编辑成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        } else {
          // 新增
          createUser(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('保存成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        }
      }
    });
  };

  /**
   * 取消
   */
  const onCancel = () => {
    editCallback();
  };

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">上传</div>
    </div>
  );

  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="user_name"
              label="用户姓名"
              rules={[{ required: true, message: '请输入用户姓名' }]}
              initialValue={params?.user_name}
            >
              <Input placeholder="请输入用户姓名" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="password"
              label="密码"
              // initialValue={params?.password}
            >
              <Input type="password" placeholder="请输入密码" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="real_name"
              label="真实姓名"
              rules={[{ required: true, message: '请输入真实姓名' }]}
              initialValue={params?.real_name}
            >
              <Input placeholder="请输入真实姓名" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="phone"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  pattern:
                    /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
                  message: '请输入正确的手机号',
                },
              ]}
              initialValue={params?.phone}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item {...formItemLayout} name="photo" label="头像" initialValue={[]}>
              <Upload {...filesProps}>
                {fileUrl === '' ? (
                  uploadButton
                ) : (
                  <img src={fileUrl} alt="data" style={{ width: '100%' }} />
                )}
              </Upload>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
