import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Button, Table, Space, Row, Col, Select, message } from 'antd';
import { apiDepartmentList, apiDepartmentUpdate } from '../service';

const { Item } = Form;

const ViewDepartmentModal = ({ visible, onClose, enterpriseList }) => {
  const [form] = Form.useForm();
  const [refForm] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [nameVisible, setNameVisible] = useState(false);
  const [enterpriseId, setEnterpriseId] = useState('');
  const [name, setName] = useState('');
  const [id, setId] = useState('');
  const [total, setTotal] = useState(0);
  const [pageInfo, setPageInfo] = useState({
    page: 1,
    size: 10,
  });

  const handleCancel = () => {
    form.resetFields();
    setDataSource([]);
    setPageInfo({ page: 1, size: 10 });
    setTotal(0);
    onClose();
  };
  const editName = row => {
    setName(row.name);
    setId(row.id);
    setNameVisible(true);
  };
  const getDepartmentList = async params => {
    const res = await apiDepartmentList(params);
    if (res.businessCode === '0000') {
      const list = res.data.records;
      setTotal(res.data.total);
      setDataSource(list);
    }
  };

  const handleSearch = async values => {
    setEnterpriseId(values.enterpriseId);
    getDepartmentList({ data: { enterpriseId: values.enterpriseId }, ...pageInfo });
  };

  const handleSave = () => {
    refForm.validateFields().then(async values => {
      const params = {
        enterpriseId,
        id,
        name: values.name,
      };
      const res = await apiDepartmentUpdate(params);
      if (res.businessCode === '0000') {
        message.success('修改成功');
        refForm.resetFields();
        setNameVisible(false);
        getDepartmentList({ data: { enterpriseId }, ...pageInfo });
      }
    });
  };
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '部门',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '创建人',
      dataIndex: 'createdBy',
      key: 'createdBy',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editName(record)}>
            修改部门名称
          </Button>
        </Space>
      ),
    },
  ];
  const onCancel = () => {
    refForm.resetFields();
    setName('');
    setNameVisible(false);
  };

  const onChange = (page, size) => {
    const json = {
      page,
      size,
    };
    setPageInfo(json);
    getDepartmentList({ data: { enterpriseId }, ...json });
  };
  const pagination = {
    ...pageInfo,
    total,
    showTotal: t => `共 ${t} 项数据`,
    onChange,
    onShowSizeChange: onChange,
  };
  return (
    <Modal visible={visible} onCancel={handleCancel} width={800} footer={null} title="查看部门">
      <Form form={form} onFinish={handleSearch}>
        <Row gutter={16}>
          <Col span={10}>
            <Item name="enterpriseId" style={{ width: '300px' }}>
              <Select
                placeholder="请选择企业"
                allowClear
                showSearch
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={enterpriseList}
              />
            </Item>
          </Col>
          <Col>
            <Item>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            </Item>
          </Col>
        </Row>
      </Form>
      <Table
        dataSource={dataSource}
        columns={columns}
        bordered
        rowKey={r => r.id}
        pagination={pagination}
      />
      <Modal
        title="修改部门名称"
        visible={nameVisible}
        footer={[
          <Button key="cancel" onClick={onCancel}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={() => handleSave()}>
            保存
          </Button>,
        ]}
        onCancel={onCancel}
      >
        <Form form={refForm}>
          {name && (
            <Form.Item
              label="部门名称"
              name="name"
              initialValue={name}
              rules={[{ required: true, message: '请填写部门名称' }]}
            >
              <Input />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </Modal>
  );
};

export default ViewDepartmentModal;
