import {
  MyBetaModalFormProps,
  MyButtons,
  MyModalFormProps,
  MyTreeCheckable,
  rulesHelper,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { useEffect } from 'react';
export default function EditPermissions(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();

  useEffect(() => {
    if (props?.item?.id) {
      Apis.Permission.SysRoles.GetPermissions({
        id: props?.item?.id ?? 0,
      }).then((res) => {
        form.setFieldsValue({
          id: props?.item?.id,
          permissions_ids: res.data?.permissions_ids,
        });
      });
    }
  }, [props?.item?.id]);

  const onSave = () => {
    let ids = form.getFieldValue('permissions_ids');
    console.log(ids);
    if (ids?.length && props.item?.id) {
      Apis.Permission.SysRoles.SetPermissions({
        permissions_ids: ids,
        id: props.item?.id || 0,
      }).then(() => {
        message.success('保存成功');
      });
    } else {
      message.error('请选择角色和勾选权限!');
    }
  };

  return (
    <>
      <div
        style={{
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
        }}
      >
        <BetaSchemaForm<ApiTypes.Permission.SysRoles.SetPermissions>
          {...MyModalFormProps.props}
          title={props.title}
          wrapperCol={{ span: 24 }}
          width="600px"
          layoutType="Form"
          form={form}
          submitter={false}
          trigger={<MyButtons.Edit title={props.title} />}
          onFinish={async (values) => {
            return Apis.Permission.SysRoles.SetPermissions({
              ...values,
              id: props.item?.id ?? 0,
            })
              .then(() => {
                props.reload?.();
                message.success('保存成功！');
                return true;
              })
              .catch(() => false);
          }}
          columns={[
            {
              key: 'permissions_ids',
              title: '选择权限',
              ...rulesHelper.array,
              renderFormItem: () => (
                <MyTreeCheckable api={Apis.Permission.SysPermissions.Tree} />
              ),
            },
          ]}
        />
        <MyButtons.Default
          key="save"
          type="primary"
          size="middle"
          title="保存"
          onClick={() => onSave()}
        />
      </div>
    </>
  );
}
