import React, { useState, useRef } from 'react';
import Table, { ProColumns, ActionType } from '@/components/Table';
import routes from '@/routes';
import DeleteButton from '@/components/Table/DeleteButton';
import { getPermission, upsertPermission } from '@/services/system/permission';
import AddPermissionModal from '../components/AddPermissionModal';
import EditPermissionModal from '../components/EditPermissionModal';

const PermissionsList = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);

  const [permissionsData, setPermissionsData] = useState(Array);
  const [isAddFirst, setIsAddFirst] = useState(false);
  const [modalData, setModalData] = useState({});
  const [rowData, setRowData] = useState({});

  const tableRef = useRef<ActionType>();

  const handleAdd = (row: any) => {
    setRowData(row);
    setIsModalVisible(true);
  };
  const handleEdit = (row: any) => {
    setRowData(row);
    setIsEditModalVisible(true);
  };

  const deleteLoopChildren = (rowData, children) => {
    debugger;
    for (let index = 0; index < children.length; index++) {
      const childrenElement = children[index];
      if (rowData.name == childrenElement.name) {
        children.splice(index, 1);
        return true;
      } else {
        if (Object.prototype.hasOwnProperty.call(childrenElement, 'children')) {
          deleteLoopChildren(rowData, childrenElement.children);
        } else {
          continue;
        }
      }
    }
  };

  const handleDelete = async (row: any) => {
    for (let index = 0; index < permissionsData.length; index++) {
      const element = permissionsData[index];
      if (row.name == element.name) {
        permissionsData.splice(index, 1);
        break;
      } else {
        const result = deleteLoopChildren(row, element.children);
        if (result) {
          break;
        }
      }
    }
    await upsertPermission(permissionsData);
    tableRef.current?.reload();
  };

  const addLoopChildren = (rowData, children) => {
    for (let index = 0; index < children.length; index++) {
      let childrenElement = children[index];
      if (rowData.name == childrenElement.name) {
        if (Object.prototype.hasOwnProperty.call(childrenElement, 'children')) {
          childrenElement = rowData;
        } else {
          childrenElement.children = rowData;
        }
        return true;
      } else {
        if (Object.prototype.hasOwnProperty.call(childrenElement, 'children')) {
          addLoopChildren(rowData, childrenElement.children);
        } else {
          continue;
        }
      }
    }
  };
  const editLoopChildren = (val, rowData, children) => {
    for (let index = 0; index < children.length; index++) {
      const childrenElement = children[index];
      if (rowData.name == childrenElement.name) {
        childrenElement.name = val.name;
        return true;
      } else {
        if (Object.prototype.hasOwnProperty.call(childrenElement, 'children')) {
          editLoopChildren(val, rowData, childrenElement.children);
        } else {
          continue;
        }
      }
    }
  };

  const columns: ProColumns<any>[] = [
    {
      title: '权限名',
      dataIndex: 'name',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 180,
      render: (_, row) => [
        <a
          key="add"
          onClick={() => {
            setIsAddFirst(false);
            handleAdd(row);
          }}
        >
          添加
        </a>,
        <a
          key="edit"
          onClick={() => {
            setModalData(row);
            handleEdit(row);
          }}
        >
          编辑
        </a>,
        Object.prototype.hasOwnProperty.call(row, 'children') ? null : (
          <DeleteButton
            key="delete"
            onDelete={() => {
              handleDelete(row);
            }}
          />
        ),
      ],
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        search={false}
        rowKey="name"
        actionRef={tableRef}
        toolBarActions={[
          {
            type: 'add',
            onConfirm: () => {
              setIsAddFirst(true);
              setIsModalVisible(true);
            },
          },
        ]}
        request={async (params) => {
          const res = await getPermission({});
          const data = JSON.parse(res.items);
          setPermissionsData(data);
          return { data: data };
        }}
      />
      <AddPermissionModal
        visible={isModalVisible}
        onCancel={function () {
          setIsModalVisible(false);
        }}
        onOk={async function (val) {
          if (isAddFirst) {
            permissionsData.push(val);
          } else {
            if (Object.prototype.hasOwnProperty.call(rowData, 'children')) {
              const result = rowData.children.find(function (value, index, arr) {
                return value.name === val.name;
              });
              if (!result) {
                rowData.children.push(val);
              } else {
                console.log('已有改权限名');
              }
            } else {
              rowData.children = [val];
            }
            for (let index = 0; index < permissionsData.length; index++) {
              const element = permissionsData[index];
              if (rowData.name == element.name) {
                permissionsData[index] = rowData;
                break;
              } else {
                const result = addLoopChildren(rowData, element.children);
                if (result) {
                  break;
                }
              }
            }
          }
          await upsertPermission(permissionsData);
          setIsModalVisible(false);
          tableRef.current?.reload();
        }}
      />
      <EditPermissionModal
        visible={isEditModalVisible}
        editModalData={modalData}
        onCancel={function () {
          setIsEditModalVisible(false);
        }}
        onOk={async function (val) {
          for (let index = 0; index < permissionsData.length; index++) {
            const element = permissionsData[index];
            if (rowData.name == element.name) {
              permissionsData[index].name = val.name;
              break;
            } else {
              const result = editLoopChildren(val, rowData, element.children);
              if (result) {
                break;
              }
            }
          }
          await upsertPermission(permissionsData);
          setIsEditModalVisible(false);
          tableRef.current?.reload();
        }}
      />
    </div>
  );
};

export default PermissionsList;
