import React from 'react';
import { Button, Card, Form, Input, Select } from 'antd';
import useBool from '@/utils/hooks/useBool';
import { getSysRole } from '@/service/sysrole';
import { postSysUser, getSysUserById } from '@/service/sysuser';
import { useSearchParams, useNavigate } from 'react-router-dom';
import Page from '@/components/Page';
import {formItemLayout, tailFormItemLayout} from '@/utils/form';
import { getSysOrg } from '@/service/sysorg';
import { getSysPosition } from '@/service/sysposition';
import Account from './Account';

const { Option } = Select;

export default (props) => {
  const [loading, startLoading, cancelLoading] = useBool();
  const [submiting, startSubmit, cancelSubmit] = useBool();
  const [open, setShow, setHidden] = useBool(false);
  const [roleList, setRoleList] = React.useState([]);
  const [orgList, setOrgList] = React.useState([]);
  const [org, setOrg] = React.useState();
  const [posList, setPosList] = React.useState([]);
  const [searchParams] = useSearchParams();
  const [form] = Form.useForm();
  const [user, setUser] = React.useState();
  const navigate = useNavigate();

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

  const onFinish = (values) => {
    const rolesList = (values.rolesList || []).map(x => ({ roleId: x }));

    startSubmit();
    postSysUser({ ...values, rolesList, userId: id }).then(res => {
      cancelSubmit();
      if (id) {
        navigate(-1);
      } else {
        navigate(`/system/user/edit?id=${res.userId}`, { replace: true })
      }
    }).catch(() => {
      cancelSubmit();
    });
  }

  React.useEffect(() => {
    getSysRole({ pageSize: 500 }).then(res => setRoleList(res.records || []));
    getSysOrg({ pageSize: 500 }).then(res => setOrgList(res.records || []));
  }, []);

  React.useEffect(() => {
    if (org) {
      getSysPosition({orgId: org, pageSize: 500}).then(res => setPosList(res.records || []));
    }
  }, [org])
  
  React.useEffect(() => {
    if (id) {
      startLoading();
      getSysUserById(id).then(res => {
        setOrg(res.orgId);
        setUser(res);
        form.setFieldsValue({
          ...res,
          rolesList: (res.rolesList || []).map(x => x.roleId),
        });
        cancelLoading();
      }).catch(() => {
        cancelLoading();
      });
    } else {
      // form.setFieldsValue({ password: '123456' });
    }
  }, [id]);

  return (
    <Page>
      <Card loading={loading}>
        <Form onFinish={onFinish} form={form} {...formItemLayout} scrollToFirstError style={{ maxWidth: '1000px' }}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[
              {
                required: true,
                message: '请填写姓名',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              {
                required: true,
                message: '请填写手机号',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="orgId"
            label="单位"
          >
            <Select onChange={setOrg}>
              {
                orgList.map(x => (
                  <Option key={x.orgId}>{x.name}</Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="positionId"
            label="岗位"
          >
            <Select>
              {
                posList.map(x => (
                  <Option key={x.positionId}>{x.name}</Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="rolesList"
            label="角色"
          >
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder="请选择角色"
            >
              {
                roleList.map(role => (<Option key={role.roleId}>{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>
            <Button disabled={!id} style={{ marginLeft: '2em' }} onClick={setShow}>
              登录账户
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Account open={open} user={user} onSuccess={setHidden} onCancel={setHidden} />
    </Page>
  )
}


