import React from 'react';
import { Button, Card, Form, Input, Select } from 'antd';
import useBool from '@/utils/hooks/useBool';
import { getRoleList } from '@/services/role';
import { saveUser, getUser } from '@/services/user';
import { useSearchParams, useNavigate } from 'react-router-dom';
import md5 from 'md5';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

const { Option } = Select;

export default (props) => {
  const [loading, startLoading, cancelLoading] = useBool();
  const [submiting, startSubmit, cancelSubmit] = useBool();
  const [roleList, setRoleList] = React.useState([]);
  const [searchParams] = useSearchParams();
  const [form] = Form.useForm();
  const userRef = React.useRef();
  const navigate = useNavigate();

  const id = searchParams.get('id');

  const onFinish = (values) => {
    const password = values.password ? md5(values.password) : undefined;
    const loginName = values.phone;
    const rolesList = (values.rolesList || []).map(x => ({ id: x }));

    startSubmit();
    saveUser({ ...values, loginName, password, rolesList, id }).then(res => {
      cancelSubmit();
      navigate(-1);
    }).catch(() => {
      cancelSubmit();
    });
  }

  React.useEffect(() => {
    getRoleList().then(setRoleList);
  }, []);
  
  React.useEffect(() => {
    if (id) {
      startLoading();
      getUser(id).then(user => {
        userRef.current = user;
        form.setFieldsValue({
          ...user,
          rolesList: (user.rolesList || []).map(x => `${x.id}`),
        });
        cancelLoading();
      }).catch(() => {
        cancelLoading();
      });
    } else {
      form.setFieldsValue({ password: '123456' });
    }
  }, [id]);

  return (
    <Card loading={loading}>
      <Form onFinish={onFinish} form={form} {...formItemLayout} scrollToFirstError>
        <Form.Item
          name="name"
          label="姓名"
          rules={[
            {
              required: true,
              message: '请填写姓名',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="dept"
          label="部门"
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
        >
          <Input />
        </Form.Item>
        <Form.Item label="账号">
          系统账号与手机号相同
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          extra={id ? '填写密码意味着重置该账户密码' : '默认密码 123456'}
          hasFeedback
        >
          <Input.Password allowClear />
        </Form.Item>
        <Form.Item
          name="rolesList"
          label="角色"
        >
          <Select
            mode="multiple"
            allowClear
            style={{ width: '100%' }}
            placeholder="请选择角色"
          >
            {
              roleList.map(role => (<Option key={role.id}>{role.name}</Option>))
            }
          </Select>
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          <Button loading={submiting} type="primary" htmlType="submit">
            保存
          </Button>
          <Button style={{ marginLeft: '2em' }} onClick={() => navigate(-1)}>
            返回
          </Button>
        </Form.Item>
      </Form>
    </Card>
  )
}


