import React, { useMemo } from "react";
import { Button, Card, Form, Input, Select, Switch } from "antd";
import useBool from "@/utils/hooks/useBool";
import { postSysUser,getSysUserById } from "@/service/sysuser";
// import { postSysUser } from "@/service/authCenter";
import { useSearchParams, useNavigate } from "react-router-dom";
import Page from "@/components/Page";
import { formItemLayout, tailFormItemLayout } from "@/utils/form";
import { getSysOrg } from "@/service/sysorg";
import UserDrawer from "./components/UserDrawer";
import SelectRole from "./components/SelectRole";
import { ProFormSwitch } from "@ant-design/pro-components";

const { Option } = Select;

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

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

  const onFinish = (values) => {
    startSubmit();

    const staffData = staffRef.current
      ? {
          hxId: staffRef.current?.hxId,
          name: staffRef.current?.name,
          avatar: staffRef.current?.avatar,
          phone: staffRef.current?.phone,
        }
      : {};

    // 把时间去掉
    const rolesList = (values.rolesList || []).map((x) => ({
      ...x,
      createDate: undefined,
      updateDate: undefined,
      createUser: undefined,
      updateUser: undefined,
    }));

    postSysUser({
      ...values,
      rolesList,
      userId: id || staffRef.current?.userId,
      ...staffData,
    })
      .then((res) => {
        cancelSubmit();
        navigate(-1);
      })
      .catch(() => {
        cancelSubmit();
      });
  };

  const onChange = (userId, staff) => {
    if (!userId) return;

    staffRef.current = staff;

    const data = {
      ...(user || {}),
      userId,
      name: staff.name,
      phone: staff.phone,
      hxId: staff.hxId,
    };

    setUser(data);
    form.setFieldsValue(data);
  };

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

  React.useEffect(() => {
    if (id) {
      startLoading();
      getSysUserById(id)
        .then((res) => {
          setUser(res);
          form.setFieldsValue(res);
          cancelLoading();
        })
        .catch((err) => {
          console.error(err);
          cancelLoading();
        });
    } else {
      // form.setFieldsValue({ password: '123456' });
    }
  }, [id]);

  return (
    <Page back>
      <UserDrawer open={open} onChange={onChange} onOpenChange={setOpen} />
      <Card loading={loading}>
        <Form
          onFinish={onFinish}
          form={form}
          {...formItemLayout}
          scrollToFirstError
          style={{ maxWidth: "1000px" }}
        >
          <Form.Item name="name" label="姓名">
            {user?.userId ? (
              <Input readOnly onClick={() => setOpen(true)} />
            ) : (
              <Button type="primary" onClick={() => setOpen(true)}>
                选择人员
              </Button>
            )}
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="hxId" label="EHR">
            <Input readOnly />
          </Form.Item>
          <Form.Item name="rolesList" label="角色">
            <SelectRole />
          </Form.Item>
          <Form.Item
            name="isAdmin"
            label="是否管理员"
            valuePropName="checked"
            normalize={(x) => (x ? 1 : 0)}
          >
            <Switch checkedChildren="开启" unCheckedChildren="关闭" />
          </Form.Item>
          <Form.Item name="orgId" label="部门">
            <Select placeholder="请选择部门" allowClear>
              {orgList.map((x) => (
                <Option key={x.orgId}>{x.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>
    </Page>
  );
};
