import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import Enumerable from 'linq';
import CreateForm from './components/CreateForm';
import api from './service';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  try {
    await api.add({ ...fields }).then((r) => {
      if (!r.data.data) {
        message.success(r.errors);
        return false;
      }
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');
  try {
    api.update(fields).then((r) => {
      if (!r.data) {
        message.error(r.errors);
        return false;
      }
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await api.remove(selectedRows.map((row) => row.id));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const Prefix = "Menu";
const menuManager = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  /** 分布更新窗口的弹窗 */
  const [stepFormValues, setStepFormValues] = useState({});
  /*绑定数据 */
  const actionRef = useRef();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  const [treeData, setTreeData] = useState();

  const [handlData, setHandlData] = useState();

  const InitTree = async () => {
    await api.trees().then((r) => {
      setTreeData(r.data);
    });
  };

  useEffect(() => {
    api.getDicData('hand_type').then(r => {
      var arr = [];
      for (var item in r.data) {
        arr.push(<Select.Option value={item}>{r.data[item]}</Select.Option>);
      }
      setHandlData(arr);
    });
  }, [])

  const Btn = (record) => {
    var arr = [];
    arr.push(<a
      onClick={() => {
        InitTree();
        handleModalVisible(true);
        setStepFormValues(record);
      }}
    >
      修改
    </a>);
    if (record.status == 1) {
      arr.push(<a
        onClick={() => {
          api.enable(record.id).then((r) => {
            actionRef.current.reload();
          });
        }}
      >
        启用
      </a>);
    }
    if (record.status == 0) {
      arr.push(<a
        onClick={() => {
          api.disable(record.id).then((r) => {
            actionRef.current.reload();
          });
        }}
      >
        禁用
      </a>);
    }
    arr.push(<a
      onClick={() => {
        api.remove([record.id]).then((r) => {
          actionRef.current.reload();
        });
      }}
    >
      删除
    </a>);
    return arr;
  }

  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    {
      title: '菜单编码',
      dataIndex: 'code',
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      hideInSearch: true,
    },
    {
      title: '菜单路径',
      dataIndex: 'router',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: { text: '启用', status: 'Success' },
        1: { text: '禁用', status: 'Warning' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => Btn(record)
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="菜单列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return <Button
            type="primary"
            key="primary1"
            onClick={() => {
              InitTree();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>
        }}
        request={async (value) => {
          let UserData = [];
          //添加机构组织
          await api.menutreepage(value).then((r) => {
            UserData = r.data;
          });
          return {
            data: UserData,
            success: true,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
          checkStrictly: false
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
        </FooterToolbar>

      )}
      <CreateForm
        treeDatas={treeData}
        dictData={handlData}
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
    </PageContainer>
  );
};

export default menuManager;
