import React from 'react';
import { Col, Form, Input, message, Modal, Row } from 'antd';
import { createRole, editRole } from '@/services/role';

const { TextArea } = Input;

interface editPros {
  visible: boolean;
  editCallback: () => void;
  params: any;
}

/**
 * 角色管理 - 编辑
 * @param props
 * @constructor
 */
const Edit: React.FC<editPros> = (props) => {
  const { params, visible, editCallback } = props;
  const [form] = Form.useForm();

  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        if (params) {
          data.record_id = params.record_id;
          editRole(data)
            .then((res) => {
              if (res && res.code === 0) {
                message.success('编辑成功');
                editCallback();
              } else {
                message.error('编辑失败');
              }
            })
            .catch((e) => {
              message.error(e?.message);
            });
        } else {
          createRole(data)
            .then((res) => {
              if (res && res.code === 0) {
                message.success('新增成功');
                editCallback();
              } else {
                message.error('新增失败');
              }
            })
            .catch((e) => {
              message.error(e?.message);
            });
        }
      }
    });
  };

  // 取消
  const onCancel = () => {
    editCallback();
  };

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 18,
    },
  };
  const formItemLayout24 = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
  };

  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="name"
              label="角色名称"
              rules={[{ required: true, message: '请输入角色名称' }]}
              initialValue={params?.name}
            >
              <Input placeholder="请输入角色名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="sequence"
              label="排序值"
              rules={[{ required: true, message: '请输入排序值' }]}
              initialValue={params?.sequence}
            >
              <Input placeholder="请输入排序值" />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout24}
              name="memo"
              label="备注"
              rules={[{ required: false, message: '请输入备注' }]}
              initialValue={params?.memo}
            >
              <TextArea rows={4} placeholder="请输入备注" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
