import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, PageHeader, Select, Spin, Tree, TreeSelect } from 'antd';
import { useRef, useState } from 'react';
import { fetchAllDepartment, addOrg, deleteOrg, updateOrg, getDataById } from './service';
import React from 'react';
const Index: React.FC<{}> = () => {
  const [spin, spinSet] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [title, setTitle] = useState<string>('');
  const [open, setOpen] = useState<boolean>(false);
  const [org, orgSet] = useState<any>([]);
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 13 },
  };
  const columns: ProColumns[] = [
    {
      title: '组织编码',
      dataIndex: 'orgNum',
      width: '10%',
    },
    {
      title: '组织名称',
      dataIndex: 'orgName',
      width: '30%',
    },
    {
      title: '组织全称',
      dataIndex: 'orgFullName',
      width: '45%',
      hideInSearch: true,
    },
    {
      title: '操作', width: '10%',
      valueType: 'option',
      render: (_, record) => [
        <Button type='text' onClick={() => { handleUpdate(record) }}>修改</Button>,
        <Button type='text' onClick={() => { handleDelete(record.orgId) }}>删除</Button>
      ]
    },
    // {
    //   title: '部门负责人',
    //   dataIndex: 'leaderName',
    //   width: '15%',
    // },
  ];
  const handleAdd = async () => {
    setOpen(true);
    setTitle('添加组织');
  };

  const handleUpdate = async (record: any) => {
    form.resetFields();
    const org = await getDataById(record.orgId);
    form.setFieldsValue(org.data);
    setOpen(true);
    setTitle('修改组织');
  };
  // 删除操作
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除该组织？',
      onOk: async () => {
        await deleteOrg(id).then((r: any) => {
          if (r.code == 200) {
            message.success('删除成功');
          }
        })
          .finally(() => actionRef.current?.reload());
      },
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (values.orgId) {
        await updateOrg(values).then((r: any) => {
          if (r.code == 200) {
            message.success('修改成功');
          }
        });
      } else {
        await addOrg(values).then((r: any) => {
          if (r.code == 200) {
            message.success('新增成功');
          }
        });
      }
      closeModal();
    } catch (error) {
      console.error(error);
    }
  };
  const closeModal = async () => {
    actionRef.current?.reload();
    form.resetFields();
    setOpen(false);
  };

  const addModal = (
    <Modal
      title={title}
      visible={open}
      width="70%"
      centered
      destroyOnClose={true}
      bodyStyle={{ maxHeight: window.innerHeight * 0.96 - 108, overflowY: 'auto', paddingTop: 0 }}
      // footer={<Button onClick={() => setOpen(false)}>关闭</Button>}
      onOk={handleSubmit}
      onCancel={() => closeModal()}
    >
      <Form form={form} {...layout}>
        <Form.Item label="组织id" name="orgId" hidden>
          <Input />
        </Form.Item>
        <Form.Item label="上级部门" name="upOrgId" >
          <TreeSelect
            style={{ width: '100%' }}
            // treeDefaultExpandedKeys={['OR1000000000']}
            placeholder="请选择部门，可搜索"
            treeData={org}
            showSearch={true}
            treeNodeFilterProp={'title'}
            allowClear
          />
        </Form.Item>
        <Form.Item label="组织名称" name="orgName" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item label="组织编码" name="orgNum" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );

  //表格请求
  async function request(params: any) {
    console.log('org params:', params);
    const { data } = await fetchAllDepartment(params);
    console.log('org data:', data);
    // orgSet(data.children);
    orgSet(data);
    let result = {
      // data: data.children,
      data: data,
      success: true,
      total: data.length,
    };
    return result;
  }


  return (
    <Spin spinning={spin}>
      <PageHeader title="组织管理" />
      <div style={{ maxHeight: innerHeight - 130, height: innerHeight - 130 }} className='xsy-entrust bgCWhite'>
        <ProTable
          actionRef={actionRef}//action触发后更新表格
          columns={columns}
          search={{ labelWidth: 'auto', span: 6 }}
          options={false}
          rowKey="orgId"
          size="small"
          pagination={false}
          toolBarRender={() => [
            <Button onClick={() => { handleAdd() }} type="primary">
              新增
            </Button>,
          ]
          }
          request={request}
        />
        {addModal}
      </div>
    </Spin >
  );
}

export default Index;
