import React, { useEffect, useState } from 'react';
import { Col, Form, Input, message, Modal, Row, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { createRole, editRole } from '@/services/role';
import { queryMenu } from '@/services/menu';

const { TextArea } = Input;

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

interface DataType {
  key: React.Key;
  name: string;
  router: string;
  record_id: string;
}

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

  // 菜单列表数据
  const getMenuList = () => {
    const data: any = {
      q: 'tree',
      query_all: 1,
    };
    queryMenu(data).then((res) => {
      if (res && res.code === 0) {
        setMenuList(res.data.list);
      }
    });
  };

  // 初始化
  useEffect(() => {
    getMenuList();
    // 获取被选中菜单的id
    if (params) {
      const arr: any = [];
      params?.menus?.forEach((item: { menu_id: any }) => {
        arr.push(item.menu_id);
      });
      setSelectedRowKeys(arr);
    }
  }, []);

  // 提交
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        if (selectedRowKeys && selectedRowKeys.length) {
          const data = { ...values };
          const arr: { menu_id: any }[] = [];
          selectedRowKeys.forEach((res: any) => {
            arr.push({ menu_id: res });
          });
          data.menus = arr;
          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);
              });
          }
        } else {
          message.error('请选择菜单权限');
        }
      }
    });
  };

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

  const handleTableSelectRow = (keys: any) => {
    setSelectedRowKeys(keys);
  };

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

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    {
      title: '访问路由',
      dataIndex: 'router',
    },
  ];

  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={24}>
            <Form.Item
              {...formItemLayout24}
              name="name"
              label="角色名称"
              rules={[{ required: true, message: '请输入角色名称' }]}
              initialValue={params?.name}
            >
              <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>
        <Table
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            onChange: handleTableSelectRow,
          }}
          columns={columns}
          rowKey={(record) => record.record_id}
          dataSource={menuList}
        />
      </Form>
    </Modal>
  );
};
export default Edit;
