import React, { 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 [value, setValue] = useState('');
  const [name, setName] = useState('');
  const [id, setId] = useState('');
  const [pagination, setPagination] = useState({
    page: 1,
    size: 10,
  });

  const handleCancel = () => {
    form.resetFields();
    onClose();
  };
  const editName = row => {
    setName(row.department);
    setId(row.id);
    setNameVisible(true);
  };

  const handleSearch = async values => {
    setPagination({ ...pagination, page: 1 });
    setValue(value);
    const res = await apiDepartmentList({ value, ...pagination });
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setDataSource(optionData);
    }
  };

  const handleTableChange = (pag, filters, sorter) => {
    setPagination(pag);
    handleSearch();
  };

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

  return (
    <Modal visible={visible} onCancel={handleCancel} width={800} footer={null} title="查看部门">
      <Form form={form} onFinish={handleSearch}>
        <Row gutter={16}>
          <Col span={10}>
            <Item name="id" 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}
        pagination={pagination}
        onChange={handleTableChange}
        bordered
      />
      <Modal
        title="修改部门名称"
        visible={nameVisible}
        footer={[
          <Button key="cancel">取消</Button>,
          <Button key="save" type="primary" onClick={() => handleSave()}>
            保存
          </Button>,
        ]}
      >
        <Form form={refForm}>
          <Form.Item
            label="部门名称"
            name="name"
            initialValues={name}
            rules={[{ required: true, message: '请填写部门名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </Modal>
  );
};

export default ViewDepartmentModal;
