import React, { useEffect, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
} from '@ant-design/pro-components';
import { Form, Modal, Tree } from 'antd';
import { useIntl, FormattedMessage } from '@umijs/max';

const RoleForm: React.FC = (props: any) => {

  const [form] = Form.useForm();
  const [treeDate, setTree] = useState([]);


  const { values, menuTree } = props;

  useEffect(() => {
    form.resetFields();
    form.setFieldsValue(values);
    setTree(!values?.sysMenuDTOS ? [] : values?.sysMenuDTOS.map((item: any) => item.id))
  }, [form, props]);

  const intl = useIntl();
  const handleOk = () => {
    form.submit();
  };
  const handleCancel = () => {
    props.onCancel();
  };
  const handleFinish = async (values: any) => {
    values.roleSort = values.roleSort ? values.roleSort : 0
    props.onSubmit(values);
  };

  return (
    <Modal
      width={640}
      title={'分配角色'}
      open={props.open}
      forceRender
      destroyOnClose
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <ProForm
        form={form}
        grid={true}
        submitter={false}
        layout="horizontal"
        onFinish={handleFinish}>
        <ProFormDigit
          name="id"
          label={'ID'}
          disabled
          hidden={true}
        />

        <ProForm.Group>
          <ProFormText
            name="roleName"
            label={'角色名称'}
            colProps={{ md: 24, xl: 24 }}
            placeholder="请输入角色名称"
            rules={[
              {
                required: true,
                message: <FormattedMessage id="请输入角色名称！" defaultMessage="请输入角色名称！" />,
              },
            ]}
          />
          <ProFormText
            name="roleKey"
            label={'权限字符'}
            colProps={{ md: 24, xl: 24 }}
            placeholder="请输入权限字符"
            rules={[
              {
                required: true,
                message: <FormattedMessage id="请输入权限字符！" defaultMessage="请输入权限字符！" />,
              },
            ]}
          />
          <ProFormText
            name="roleSort"
            label={'排序'}
            colProps={{ md: 24, xl: 24 }}
            placeholder="请输入排序字符"
            fieldProps={{
              defaultValue: 0
            }}
          />

        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item label="菜单权限" name="menuIds">
            <Tree
              checkable
              fieldNames={{
                title: 'label',
                key: 'id',
              }}
              defaultCheckedKeys={treeDate}
              treeData={menuTree}
              onCheck={(e) => {
                setTree(e)
                form.setFieldsValue({ menuIds: e });
              }}
            />
          </ProForm.Item>
        </ProForm.Group>
      </ProForm>
    </Modal>
  );
};

export default RoleForm;
