import React, { useState, useEffect } from 'react';
import { Button, Table } from 'antd';
import { connect, useNavigate } from 'umi';
import AuditModal from './AuditModal';
import { PageContainer, ProCard } from '@ant-design/pro-components';

function Audit(props) {
  const { list = [], classify = [], dispatch, loading } = props;
  let navigate = useNavigate();
  const [visible, setVisible] = useState({
    audit: false,
    auditNode: false,
  });
  const columns = [
    {
      title: '审批流名称',
      dataIndex: 'name',
    },
    {
      title: '分类',
      dataIndex: 'classify_id',
      render: (id) => classify?.find((item) => item.id == id)?.name || '-',
    },
    {
      title: '操作',
      render: (item, index) => (
        <>
          <a
            onClick={() => {
              setCurrentNode(item);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];
  const handleAuditOk = (values) => {
    dispatch({
      type: 'flow/addAudit',
      payload: {
        ...values,
        flow_type: 1,
      },
      callback: () => {
        changeVisible('audit', false);
      },
    });
  };
  const changeVisible = (type, visible) => {
    setVisible({
      ...visible,
      [type]: visible,
    });
  };
  const setCurrentNode = (item) => {
    localStorage.setItem('currentAudit', JSON.stringify(item));
    dispatch({
      type: 'flow/save',
      payload: {
        current: item.list,
      },
    });
    navigate('/flow/audit');
  };

  useEffect(() => {
    dispatch({
      type: 'flow/queryAuditList',
      payload: {
        flow_type: 1,
      },
    });
    dispatch({
      type: 'flow/queryClassify',
      payload: {
        c_type: 1,
      },
    });
  }, []);

  return (
    <PageContainer
      title={null}
      breadcrumb={null}
      extra={[
        <Button
          key={1}
          onClick={() => changeVisible('audit', true)}
          type="primary"
        >
          新建流程
        </Button>,
      ]}
    >
      <ProCard>
        <Table
          loading={loading['flow/queryAuditList']}
          rowKey="id"
          dataSource={list}
          columns={columns}
        />
      </ProCard>

      <AuditModal
        loading={loading['flow/addAudit']}
        visible={visible.audit}
        onOk={handleAuditOk}
        onCancel={() => changeVisible('audit', false)}
        classify={classify}
      />
    </PageContainer>
  );
}
export default connect(({ flow, loading }) => ({
  list: flow.auditList,
  classify: flow.classify,
  loading: loading.effects,
}))(Audit);
